我正在尝试让我的Vue-Router记住输入URL,并在登录后转到那里。这段代码在无限循环中结束时一直有效,直到倒数next()
为止,而我不知道为什么。
在下面的代码中,我在<----- why infinite loop (?)
处添加了注释,我也尝试过next({ fullPath: url})
,即使我检查并将entryUrl设置为测试条目{{1, }}
示例路径:
/requests
beforeEach块:
{
path: "/requests",
name: "My Requests",
component: Requests,
meta: { requiresAuth: true },
},
通过无限循环,我的意思是它会执行此操作,直到遇到“最大调用堆栈大小超出”错误为止。这些值只是控制台日志:
let entryUrl = null;
router.beforeEach((to, from, next) => {
let locStorage = JSON.parse(localStorage.getItem("userData"));
let stateStore = state.getters.getUserData;
let userData = locStorage || stateStore;
let isAuthenticated = userData.token !== "" && userData.token !== undefined;
// if entry url not "/login" or "/" set entryUrl
if (to.fullPath !== "/login" && to.fullPath !== "/") {
entryUrl = to.fullPath;
}
// if path requires auth
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!isAuthenticated) {
// needs auth, none found, send to "/login"
next({ name: "Login" });
} else {
// needs auth, has auth, check for entryUrl
let url = entryUrl ? entryUrl : "/";
entryUrl = null;
next(url); // <-------------------------- why infinite loop (?)
}
} else {
// no auth required ("/login" only in my case)
next();
}
});
export default router;