fncheng / vue-learn

0 stars 0 forks source link

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

Open fncheng opened 3 years ago

fncheng commented 3 years ago

预期: 使用beforeEach 时,判断用户是否登录;已登录,则next()跳转至相应页面;未登录,则跳转至登录页

代码:

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

实际表现:以上会导致路由无限循环

原因:

也就是说beforeEach()必须调用next(),否则就会出现无限循环。

官网是这样说明的:

next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。