关于vue-router的beforeEach无限循环的问题

最近在使用vue-router的beforeEach钩子时候遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题
代码以下:vue

// isLogined 用来判断用户是否已登陆
router.beforeEach((to, from, next) => {
  if(isLogined){
    next()
  }else{
    console.log('测试')
    next('login')
  }
})

结果chrome的debug中看到:vue-router

clipboard.png

这个问题我是这样理解的:chrome

router.beforeEach((to, from, next) => {
    if(true){
        next()
    }else{
        next('login')
    }
})
  • next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()
  • next('login') 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()

也就是说beforeEach()必须调用next(),不然就会出现无限循环,
next() 和 next('xxx') 是不同的,区别就是前者不会再次调用router.beforeEach(),后者会!!!测试

官网这样写的(主要是红线标记的那句!):spa

clipboard.png

So.... 若是为你解惑了,点个赞呗~ 若是我理解的有误,请指正~debug

相关文章
相关标签/搜索