搜尋

首頁  >  問答  >  主體

導航守衛遇到無限重定向錯誤:未捕獲(承諾)

我有一個使用以下路由定義的 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粉291886842341 天前394

全部回覆(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
  • 取消回覆