Vue路由拦截

Vue.js+webpack构建的项目,没有使用vuex

怎么在没有登陆的时候直接跳转到用户登陆界面进行登陆?

没有登陆就禁止访问其他界面

vue-router该怎么控制

阅读 28.8k
8 个回答
  1. 在登陆的时候在本地cookie存储一个isLogin=true,未登录为false;
  2. 在路由页router.js里面,写好beforeEach((to, from, next),根据to.name来判断接下来去那个页面,以及isLogin是否为true;不符合要求的页面全部跳转到login页面;

比如:

 if (!isLogin && to.name !==(不需要需要登陆的页面)){
        next({
            name: 'login',
        })
    }else {
        if (is_login && toName === 'login') {
            next({
                path: '/'
            })
        } else {
            next()
        }
    }

代码可能有点问题,但意思是这么个意思

const whiteList = ['/login', '/authredirect']// 免登录白名单

router.beforeEach((to, from, next) => {
  if (cookieGetToken()) { // determine if there has token
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
    }
    next()
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
    }
  }
})

文档

贴代码和注释

const whiteList=['/login'];//不需要登录能访问的path
router.beforeEach((to, from, next) => {
  console.log('beforeEach');
  var userInfo= JSON.parse(sessionStorage.getItem('userInfoStorage'));//获取缓存看是否登录过
  if(whiteList.indexOf(to.path)<0){//访问了需要登录才能访问的页面
    if(userInfo){//登录过来直接进去
      next();
    }else{
      if(to.path=='/login'){
        next();
      }else{
        next('/login');
      }
    }
  }
  else{
    next();
  }
});

router.beforeEach里面判断是否已经登录,没有登录则跳转到登录页面

router.beforeEach((to, from, next) => {


next(); //前往下一个页面

})

router.afterEach(transition => {

});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题