gpt4 book ai didi

javascript - 为什么 "Redirected when going from "/login"to "/"via a navigation guard."出现了?

转载 作者:行者123 更新时间:2023-12-05 02:02:13 25 4
gpt4 key购买 nike

router guard 在我的 vue 应用程序上运行良好,但登录后,控制台出现以下错误。

Uncaught (in promise) Error: Redirected when going from "/login" to "/" via a navigation guard.

这是我的代码片段。

const routes = [
{
path: "/login",
component: () => import("../views/Auth/Login"),
meta: { hideForAuth: true },
},
{
path: "/",
component: DashboardLayout,
meta: { requiresAuth: true },
children: [
{
path: "home",
name: "Home",
component: () => import("../views/Home"),
},
],
},
];

Auth 守卫:

const loggedIn = localStorage.getItem("auth");

router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!loggedIn) {
next({ path: "/login" });
} else {
next();
}
} else {
next();
}

if (to.matched.some((record) => record.meta.hideForAuth)) {
if (loggedIn) {
next({ path: "//" });
} else {
next();
}
} else {
next();
}
});

无法找出问题所在。提前致谢!

最佳答案

由于 next 不会退出守卫,守卫将在每条路线上至少调用 next 2 次,因为您有 2 个单独的 if语句,两者都将运行。

  • //路径改为/
  • return next 一样调用 next 来退出函数,或者构造你的 if 语句,这样只有一个会运行。
  • 在 guard 中设置 loggedIn 否则只会在创建路由器时计算一次

这是一种方法,它也涵盖没有 meta 的路由:

router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem("auth");
const isAuth = to.matched.some((record) => record.meta.requiresAuth);
const isHide = to.matched.some((record) => record.meta.hideForAuth);

if (isAuth && !loggedIn) {
return next({ path: "/login" });
} else if (isHide && loggedIn) {
return next({ path: "/" });
}
next();
});

关于javascript - 为什么 "Redirected when going from "/login"to "/"via a navigation guard."出现了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66010046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com