[英]Vue-Router infinite loop with redirect route
我正在嘗試找到將未經身份驗證的用戶重定向到登錄頁面/屏幕的最佳方法。 目前,我正在嘗試在加載組件之前在路由中使用 JWT 令牌進行身份驗證。 但是,我在router.beforEach()
上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();
}
但這會調用兩次警報,似乎是一種低效和/或笨拙的方法來解決這個問題。 有沒有比這更好的方法來測試路線的條件? 感謝您的任何提示,建議,幫助
我不認為這是 hacky。
if (to.path !== '/login') {
next('/login');
}
當你改變路由時,它自然router.beforeEach
再次觸發router.beforeEach
。
你可以把它移到上面if (to.matched.some(r => r.meta.requiresAuth)) {
以避免做不必要的檢查
if (to.path === '/login') {
next();
}
另一種方法是使用window.location
跳出SPA
,但我認為這不是更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.