我正在为一些网址创建一个守卫。我使用 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
条件内:
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 [a return statement after
next()
]
这是因为您发现的每个示例都避免在导航保护处理程序中使用我们在 JavaScript 中找到的常用逻辑多次调用 next()
,例如显式 else
就像你正在使用的那样。
关于javascript - Vue Router next 回调总是在 beforeEach 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51881872/