Vue 路由守卫

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to: Route: 即将要进入的目标 路由对象
  // from: Route: 当前导航正要离开的路由
  // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  console.log(to)
  const nextRoute = [
    '/home/chatroom?selectSelfCreate=true',
    '/home/createchatroom'
  ];
  var sessionData = session.get("notlogin");
  var notlogin = true;
  if (sessionData) {
    notlogin = eval(sessionData);
  } else {
    notlogin = true;
  }
  // 未登录状态;当路由到nextRoute指定页时,跳转至login
  if (nextRoute.indexOf(to.fullPath) >= 0) {
    if (notlogin) {
      console.log('未登录')
      router.push({
        name: 'login'
      });
      return;
    }
  }
  // 已登录状态;当路由到login时,跳转至home 
  if (to.name === 'login') {
    if (!notlogin) {
      router.push({
        name: 'luntancontent'
      });
      return;
    }
  }
  next();
});

猜你喜欢

转载自www.cnblogs.com/chenyishi/p/9208448.html