Vue Router next 回调总是在 beforeEach 中调用

Vue Router next callback always called in beforeEach

我正在为某些网址创建防护。我正在使用 beforeEach 评估元参数并决定用户是否可以看到页面。

router.beforeEach((to, from, next) => {
  var isLoggedIn = localStorage.getItem('cacheTokenId');

  if(to.meta.guestOnly && isLoggedIn) {
    next({ name: 'cars' })
  } else if(to.meta.authOnly && !isLoggedIn) {
    console.log("authOnly")
    next({ name: 'login' })
  }

  next()
})

我的问题是最后一个 next(外部条件)总是被执行。我以为 next() 在它被调用的地方停止了执行。

目前,我的解决方案在 else 条件下最后 next() 移动:

if(to.meta.guestOnly && isLoggedIn) {
    console.log("guestOnly")
    next({ name: 'cars' })
  } else if(to.meta.authOnly && !isLoggedIn) {
    console.log("authOnly")
    next({ name: 'login' })
  } else {
    next()
  }

为什么需要这个,我是不是遗漏了什么?

I thought next() stopped the execution at the point where it was called.

next() 只是一个函数调用,它不会做语言规范之外的事情。它不会抛出异常,因此不会停止流程。

all examples I have found does not have

这是因为您发现的每个示例都避免在导航守卫处理程序中多次调用 next(),并使用我们在 JavaScript 中找到的常用逻辑,例如显式 else ] 就像你正在使用的那样。