当我使用beforeEach与子路径调试控制台一起显示此错误时:vue-router.esm.js?8c4f:2079 RangeError:超出了最大调用堆栈大小
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginMixin from '@/mixins/LoginMixin.js'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: require('@/views/Home.vue').default,
},
{
path: '/login',
name: 'login',
meta: { layout: 'centered' },
component: () => import('@/views/Login.vue'),
},
{
path: '/register',
name: 'register',
meta: { layout: 'centered' },
component: () => import('@/views/Register.vue'),
children: [
{
path: 'user',
component: () => import('@/components/RegisterForm.vue'),
},
{
path: 'company',
component: () => import('@/components/CompanyForm.vue'),
}
]
},
]
//creamos la instancia router modo history(urls amigables)
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
router.beforeEach((to, from, next) => {
if (to.path != '/login' || to.path != '/register/user' && LoginMixin.methods.loginMixinCheckAuth() == false) {
//if not logead and join to other page distinc of login or register redirect to login
next('/login')
}
else {
next()
}
})
我不知道有什么不好,语法还可以,并且函数LoginMixin.methods.loginMixinCheckAuth()正常工作(我测试了该函数,结果相同)。
答案 0 :(得分:0)
嗯,乍一看,我会尝试简化您的if
方法中这个复杂的beforeEach
。尝试将requiresAuth: true
之类的内容添加到所有需要登录用户的路由的元中。
从某种意义上说,您在路线中需要这样的东西:
// ...
{
path: '/users/:userId(\\d+)/edit/',
name: 'EditUser'
props: true,
meta: {
requiresAuth: true, // <-- add this meta flag against which you check later in beforeEach
},
component: () => import(/* webpackChunkName: "user-edit" */ '@/views/UserEdit.vue'),
},
// ...
这在您的beforeEach
中:
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) { // <-- check for requiresAuth here
// assuming your login mixin works
// if I were you I'd store some JWT in localStorage and check that somehow in a vuex getter
if (!LoginMixin.methods.loginMixinCheckAuth()) {
next('/login')
} else {
next()
}
} else {
next()
}
})
要完全回答这个问题会比较麻烦,因此请检查一下我如何使用meta
here并实现了beforeEach
rule here