0
点赞
收藏
分享

微信扫一扫

路由拦截代码

棒锤_45f2 2022-02-16 阅读 63
//登录页


Login() {
      let _this = this;
      if (!_this.loginForm.UserName || !_this.loginForm.PassWord) {
        _this.$message.warning("请填写完整用户名或密码!");
        return;
      }


        // 点击登录时储存登录令牌user
        localStorage.setItem("user", _this.loginForm.PassWord);
        // 跳转到home页
        _this.$router.replace({path: "/home",})
        // 提示消息
        _this.$message.success("登录成功!");
      
}


//index.js(定义路由的文件)

//在需要拦截的路由里添加meta字段
{ path: '/home',
      component: home, 
      meta: {
        requireAuth: true,  // 添加该字段,表示进入这个路由是需要登录的
      },
},


min.js中


router.beforeEach((to, from, next) => {
  
  if (to.matched.some((r) => r.meta.requireAuth)) {
    let user = localStorage.user
    if (user) { // 判断是否已经登录(user存在则正常跳转)
      next()
    } else {
      next({
        path: '/',
        query: { redirect: to.fullPath } // 登录成功后重定向到当前页面
      })
    }
  } else {
    next()
  }

  // 如果本地存在 user(即已登录) 则 不允许直接跳转到 登录页面(可去掉)
  if (to.fullPath === '/login1') {
    if (localStorage.user) {
      next({
        path: '/home'
      })
    } else {
      next()
    }
  }


})
举报

相关推荐

0 条评论