请问一下,用vue-router跳转一个页面,然后router.beforeEach触发了两次是为什么啊

问题描述

我在整合一个项目的前后台时候,后台的登录页面“http://localhost:8080/#/Manage_Login/”会自动跳转为”http://localhost:8080/#/Index“,然后我没有用路由的重定向,后来发现是router.beforeEach触发了两次,请问是为什么啊

问题出现的环境背景及自己尝试过哪些方法

相关代码

router.beforeEach((to, from, next) => {
  var data = JSON.parse(localStorage.getItem('key'));
  console.log('to', to,'from', from)
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (data) {    
      next();
    } else {
      var state = localStorage.getItem('state');
      //企业微信
      if (state === 0) {
        next({
          path: '/ErrorPage/登录已失效,请重新登录!'
          // query: {redirect: to.fullPath}
        })
      } else {
       
        next({
          path: '/Login',
          query: {
            redirect: to.fullPath
          }
        })
      }
    }
  } else {
    console.log(1)
    next();
  }
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  console.log(2)
  // next()
})

触发了两次router.beforeEach

clipboard.png

阅读 9.6k
3 个回答
新手上路,请多包涵

确实是有这么个问题,这个需要看下源码理解下,这三个参数有顺序的。

出问题的代码如下:

router.beforeEach((to, from, next) => {
    var user = JSON.parse(sessionStorage.getItem('user'));
    if(user == null){
       next({ path: '/login' }); // 没有用户,就跳去登录
    } else {
       next();
    }
});

看似是如果 usernull 就跳转到 '/login' 这个路由中去,但是 to, from, next 三个变量的执行顺序得明确下:

首先路由会先到 to.path
然后检查 next.path 有没有值,如果没有,则不跳转,若有,向 next.path 这个值跳转。

现在这样一个情况出现了,假定 to.path == '/login',

在刚才代码的情况下, 路由首先跳到 /login, 然后检查 next, 发现 next 里面的 path'/login', 不为空,那么就继续跳 next.path 这个路由, 也就是 '/login',这次跳的时候,to.path 就是又设置为 '/login' 了, 那么就又回到开始的情况了,于是死循环。

那么怎么避免这种情况发生呢,很简单,每次我们要改变跳转的时候,也就是要给next.path 赋值的时候,只要这个to.path的值相同,那么,就不要赋值了,赋值就死循环。

所以正确的代码如下:

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

    var user = JSON.parse(sessionStorage.getItem('user'));
    if(user == null){
        if(to.path == '/login'){ // 如果to.path 的值和我们要跳转的值相同,不要赋值
            next();
        } else {
            next({ path:'/about' });
        }
    } else {
        next();
    }
});

不是这些问题,我页面写错了,谢谢

推荐问题