带有重定向路由的 Vue-Router 无限循环
Vue-Router infinite loop with redirect route
我正在尝试找到将未经身份验证的用户重定向到登录 page/screen 的最佳方法。目前我正在尝试在加载组件之前在路由中使用 JWT 令牌捕获身份验证。但是,我在 router.beforEach()
上陷入无限循环:
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requiresAuth)) {
alert('needs auth!'); // used for testing
if (localStorage.getItem('jwt') == null) {
next('/login'); // here is where the infinite loop hits
} else {
next();
}
} else {
next();
}
});
当我到达需要验证的路由时,next('/login')
调用陷入无限循环。我可以这样避免这种情况:
if (to.path !== '/login') {
next('/login');
} else {
next();
}
但这会调用警报两次,似乎是一种低效的 and/or 处理此问题的怪异方法。有没有比这更好的方法来测试路线的条件?感谢您提供任何提示、建议和帮助
我不认为这是 hacky。
if (to.path !== '/login') {
next('/login');
}
随着你改变路线,自然会再次触发router.beforeEach
。
您可以将其移至 if (to.matched.some(r => r.meta.requiresAuth)) {
上方,以避免使用
进行不必要的检查
if (to.path === '/login') {
next();
}
另一种方法是用 window.location
跳出 SPA
,但我不认为那样更好。
我正在尝试找到将未经身份验证的用户重定向到登录 page/screen 的最佳方法。目前我正在尝试在加载组件之前在路由中使用 JWT 令牌捕获身份验证。但是,我在 router.beforEach()
上陷入无限循环:
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requiresAuth)) {
alert('needs auth!'); // used for testing
if (localStorage.getItem('jwt') == null) {
next('/login'); // here is where the infinite loop hits
} else {
next();
}
} else {
next();
}
});
当我到达需要验证的路由时,next('/login')
调用陷入无限循环。我可以这样避免这种情况:
if (to.path !== '/login') {
next('/login');
} else {
next();
}
但这会调用警报两次,似乎是一种低效的 and/or 处理此问题的怪异方法。有没有比这更好的方法来测试路线的条件?感谢您提供任何提示、建议和帮助
我不认为这是 hacky。
if (to.path !== '/login') {
next('/login');
}
随着你改变路线,自然会再次触发router.beforeEach
。
您可以将其移至 if (to.matched.some(r => r.meta.requiresAuth)) {
上方,以避免使用
if (to.path === '/login') {
next();
}
另一种方法是用 window.location
跳出 SPA
,但我不认为那样更好。