我有一个用以下路由定义的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"),
},
];
我试图实现一个谷歌认证登录功能,其中/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
页。
当cms
已经是当前路由时,做next({ name: "cms" })
是错误的。它应该是next()
,然后else if
变得多余:
if (!store.state.loggedIn && to.name === "cms") {
return next({ name: "login" });
}
else {
return next();
}