Vue-router:未捕获的范围错误:超过最大调用堆栈大小

zpqajqem  于 2023-08-07  发布在  Vue.js
关注(0)|答案(1)|浏览(148)

我尝试使用router.beforeEach()在每次转换之前检查用户是否登录,如果没有,我想将他重定向到登录页面。我试过了

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const currentUser = store.state.currentUser;

    if(requiresAuth && !currentUser) {
        next('/login');
    } else if(to.path == '/login' && currentUser) {
        next('/home');
    } else {
        next();
    }
});

字符串
但返回错误:未捕获的范围错误:超出了最大调用堆栈大小,这是我的路由:

export const routes = [
{path: '/', component: Main ,meta: {requiresAuth: true},children:[
    {path: '/project', component: project , meta: {requiresAuth: true} },
    {path: '/calendrier', component: calendar, meta: {requiresAuth: true} },
    {path: '/setting', component: setting, meta: {requiresAuth: true} },
    {path: '/client', component: client, meta: {requiresAuth: true} },
    {path: '/detail/:id', name: detail , component: detail, meta: {requiresAuth: true} },
    {path: '/membre', component: membre, meta: {requiresAuth: true} },
    {path: '/test', component: test, meta: {requiresAuth: true} },
    {path: '/projectemploye' , component: projectemploye, meta: {requiresAuth: true} },
    {path: '/Chefprojet', component: chef, meta: {requiresAuth: true}},
    {path: '/client/:id' , component: clientdetail, meta: {requiresAuth: true} },
    {path: '*' , component:    require('./components/404.vue').default , meta: {requiresAuth: true}},
    {path: '/home' , component: home , meta: {requiresAuth: true}},
    {path: '/gantt/:id' , component: gantt, meta: {requiresAuth: true}},
    {path: '/reclamation' , component: reclamation, meta: {requiresAuth: true}},
    {path: '/detailleReclamation/:id' , component: DetailleReclamation, meta: {requiresAuth: true}},
    {path: '/profile/:id' , component: profile , meta: {requiresAuth: true}},
    {path: '/task/:id' , component: task, meta: {requiresAuth: true}},
    {path: '/taskdetail/:id' , component: taskdetail, meta: {requiresAuth: true} }
    ]
 },
{path: '/login', component: Login},

 ];

n53p2ov0

n53p2ov01#

路径为*的路由:
1.不能是任何其他路由的子项
1.必须是路由数组中的最后一个
1.其元数据中不得包含requiresAuth: true
根路由/元数据中不能包含requiresAuth: true
在这种情况下,不需要将所有路由都列为根路由的子路由。
如果你的所有路由都是受保护的,只有/login是公共的,那么最好将你的逻辑从正逻辑切换到负逻辑。这意味着,与其将requiresAuth: true放在除/login之外的所有路由上,不如将public: true放在/login中,并将所有其他路由的元数据保留为空。
然后检查!meta.public而不是meta.requiresAuth

相关问题