好资源导航 » 文章资讯 » 使用Vue-Router的导航守卫-无限循环问题

使用Vue-Router的导航守卫-无限循环问题

我在项目里面用到了的是全局守卫,beforeEach,方便管理
不过遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题
当时的代码如下:

router.beforeEach((to, from, next) => {
    if (isLogin) {
      next()
    } else {
      console.log('测试')
      next('login')
    }
}) 

这个问题我是这样理解的:
next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()
next(‘login’) 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()
也就是说beforeEach()必须调用next(),否则就会出现无限循环,next() 和 next(‘xxx’) 是不一样的,区别就是前者不会再次调用router.beforeEach(),后者会!!!

最终解决的代码如下:

router.beforeEach((to, from, next) => {
    if (isLogin) {
      next()
    } else {
      if (to.name === 'login') {
        next()
      } else {
        console.log('测试')
        next('login')
      }
    }
}) 

热门推荐