我试图在我的应用程序中设置一些用户可以和不能访问的路由,但有时我的浏览器会冻结并且不会给我任何错误消息,所以我不知道我在做什么错了。
在第一个 IF 中,我检查路由是否需要身份验证为 true 才能访问,如果为 false,我将用户发送到登录页面。然后我检查用户所在的组,如果失败,则重定向到根页面“/”。如果这些 IF 语句都不成立,我只会重定向到用户想要导航到的页面。
router.beforeEach((to, from, next) => {
const isAuth = localStorage.getItem("auth");
const userGroupRaw = localStorage.getItem("userData");
const accessGroup = to.meta.group;
let userGroup;
if (userGroupRaw) {
userGroup = JSON.parse(userGroupRaw).id_access;
}
if (to.matched.some((record) => record.meta.requiresAuth)) {
console.log("if1");
if (isAuth === "false") {
next({ path: "/login" });
}
if (
(accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
!userGroup
) {
next({ path: "/" });
}
next();
}
next();
});
export default router; Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
由于您没有使用“else”语句,因此您多次调用
next()并陷入无限循环(如评论中所述)。您可以使用
return来在此时停止代码。router.beforeEach((to, from, next) => { const isAuth = localStorage.getItem("auth"); const userGroupRaw = localStorage.getItem("userData"); const accessGroup = to.meta.group; let userGroup; if (userGroupRaw) { userGroup = JSON.parse(userGroupRaw).id_access; } if (to.matched.some((record) => record.meta.requiresAuth)) { if (isAuth === "false") { return next({ path: "/login" }); } if ( (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) || !userGroup ) { return next({ path: "/" }); } // next(); - this is not needed as the preceding next always gets called. } next(); }) export default router;