搜索

首页  >  问答  >  正文

导航守卫遇到无限重定向错误:未捕获(承诺)

我有一个使用以下路由定义的 vue3 路由器

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  {
    path: "/gallery",
    name: "gallery",
    component: () =>
      import(/* webpackChunkName: "gallery" */ "../views/GalleryView.vue"),
  },
  {
    path: "/cms",
    name: "cms",
    component: () =>
      import(/* webpackChunkName: "cms" */ "../views/CmsView.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "cms" */ "../components/Login/LoginPage.vue"),
  },
];

我正在尝试实现 Google 身份验证登录功能,其中只有特定帐户登录后才能访问 /cms 路径。我在商店中有一个名为loggedIn 的布尔值,它将在组件中翻转为 true 。如图

<script setup>
import { decodeCredential, googleLogout } from "vue3-google-login";
import store from "@/store/index";
import router from "@/router/index";
const callback = (response) => {
  const userData = decodeCredential(response.credential);
  if (userData.email === "my_email") {
    store.state.loggedIn = true;
    router.push({ path: "/cms" });
  } else {
    store.state.loggedIn = false;
    googleLogout();
  }
};
</script>

在路由器中,我正在执行 beforeEach 操作,根据用户来自何处以及特定用户是否登录(如图所示)来检查要路由到哪个页面。

router.beforeEach(async (to, from, next) => {
  // If not logged in and trying to access cms
  if (!store.state.loggedIn && to.name === "cms") {
    return next({ name: "login" });
  }
  // If logged in and trying to access cms after login
  else if (store.state.loggedIn && to.name === "cms" && from.name === "login") {
    console.log("test");
    return next({ name: "cms" });
  }
  // Else just route to next page
  else {
    return next();
  }
});

一切似乎都正常,除非正确的用户登录。未捕获(承诺)错误:导航防护中抛出无限重定向,并且页面未重定向到 /cms 而是选择留在 /login页面。

P粉291886842P粉291886842349 天前401

全部回复(1)我来回复

  • P粉165823783

    P粉1658237832023-12-30 00:39:57

    cms 已经是当前路由时,执行 next({ name: "cms" }) 是错误的。它应该是 next(),然后 else if 就变得多余了:

    if (!store.state.loggedIn && to.name === "cms") {
        return next({ name: "login" });
      }
      else {
        return next();
      }

    回复
    0
  • 取消回复