我有一个非常简单的路由,实际上是这样的,我在电子下使用它
import Vue from "vue";
import VueRouter from "vue-router";
import Projects from "../views/Projects.vue";
import RegisterUser from "@/views/RegisterUser.vue";
//import { appHasOwner } from "@/services/";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "projects",
component: Projects,
meta: {
requiresUser: true
}
},
{
path: "/register",
name: "register",
component: RegisterUser
},
{
path: "/settings",
name: "settings",
meta: {
requiresUser: true
},
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/Settings.vue")
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.requiresUser === true)) {
//this will be for test case undefined
let user;
if (typeof user === "undefined") {
// eslint-disable-next-line no-console
console.log(user); //logs undefined but at the end no redirect
next("/register");
} else {
next();
}
}
});
export default router;
以文档中的示例为例
// GOOD
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next('/login')
else next()
})
仅当数据库中有附加用户时,应用程序才能启动,或者应该重定向到注册组件,但是以上代码以Maximum call stack size exceeded
结尾。那么如何检查beforeEach
条件是否可以重定向到给定页面?
答案 0 :(得分:2)
Maximum call stack size exceeded
通常是由于无限递归所致,在这里确实确实是如此。在router.beforeEach
中,您要调用next
转到/register
路由,该路由又回到此方法中,该方法调用next
,依此类推。我看到您的requiresUser
中有一个meta
,因此您需要在beforeEach
中进行检查,如下所示:
router.beforeEach((to, from, next) => {
// If the route's meta.requiresUser is true, make sure we have a user, otherwise redirect to /register
if (to.matched.some(route => route.meta.requiresUser === true)) {
if (typeof user == "undefined") {
next({ path: '/register' })
} else {
next()
}
}
// Route doesn't require a user, so go ahead
next()
}