首页 > 解决方案 > 为什么“通过导航守卫从“/login”转到“/”时重定向。” 正在出现?

问题描述

在这里,路由器保护在我的 vue 应用程序上工作正常,但登录后,控制台上出现以下错误。

未捕获(承诺)错误:通过导航守卫从“/login”转到“/”时重定向。

这是我的代码片段。

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();
  }
});

无法弄清楚问题所在。提前致谢 !

标签: javascriptvue.jsvuejs2local-storagevue-router

解决方案


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

  • //将路径更改为/
  • call nextlikereturn next退出函数,或者构造你的if语句,以便只有一个会运行。
  • 设置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();
});

推荐阅读