使用 Vue Js 路由器超过最大调用堆栈
Maximum Call Stack Exceed Using Vue Js Router
我和这里的其他人一样遇到了常见问题,我尝试按照他们的解决方案进行操作,但我仍然无法解决。在我的应用程序中,我需要先登录,然后 select 公司,然后才能进入主页。我的登录没问题,我的问题出在 select 公司。如果他们没有选择公司,我需要附加一个警卫来阻止他们访问主页。我所做的是检查本地存储,如果 selectCorporation 是空的,那么我将能够知道他们已经 selected 了一个公司。
const router = new Router({
mode: 'history',
routes: [
{ path: '/', name: 'overview', component: Overview },
// Authentication
{ path: '/auth/login', name: 'auth.login', component: Login, meta: { requiresVisitor: true }},
//Select Corporation
{ path: 'select-corporation', name: 'corporations.select', component: CorporationsSelect }
// Branches
{ path: '/branches', name: 'branches.index', component: BranchesIndex },
{ path: '/branches/create', name: 'branches.create', component: BranchesCreate },
{ path: '/branches/:id', name: 'branches.view', component: BranchesView },
{ path: '/branches/:id/edit', name: 'branches.edit', component: BranchesEdit },
});
router.beforeEach((to, from, next) => {
if (localStorage.getItem('selectedCorporation') === null) {
next({
path: '/select-corporation'
});
} else {
next({
path: '/branches'
});
}
});
export default router;
检查您的目标路由是否 select-corporation
以中断无限重定向循环,如果已经选择公司,"else" 块也会导致相同的行为:
router.beforeEach((to, from, next) => {
if (localStorage.getItem('selectedCorporation') === null) {
// checking to avoid loop
if (to.name === 'corporations.select') return next();
next({
path: '/select-corporation'
});
}
else {
next();
}
});
如果您想在选择公司后将用户重定向到 branches
页面,只需在 CorporationsSelect
中执行即可。
我和这里的其他人一样遇到了常见问题,我尝试按照他们的解决方案进行操作,但我仍然无法解决。在我的应用程序中,我需要先登录,然后 select 公司,然后才能进入主页。我的登录没问题,我的问题出在 select 公司。如果他们没有选择公司,我需要附加一个警卫来阻止他们访问主页。我所做的是检查本地存储,如果 selectCorporation 是空的,那么我将能够知道他们已经 selected 了一个公司。
const router = new Router({
mode: 'history',
routes: [
{ path: '/', name: 'overview', component: Overview },
// Authentication
{ path: '/auth/login', name: 'auth.login', component: Login, meta: { requiresVisitor: true }},
//Select Corporation
{ path: 'select-corporation', name: 'corporations.select', component: CorporationsSelect }
// Branches
{ path: '/branches', name: 'branches.index', component: BranchesIndex },
{ path: '/branches/create', name: 'branches.create', component: BranchesCreate },
{ path: '/branches/:id', name: 'branches.view', component: BranchesView },
{ path: '/branches/:id/edit', name: 'branches.edit', component: BranchesEdit },
});
router.beforeEach((to, from, next) => {
if (localStorage.getItem('selectedCorporation') === null) {
next({
path: '/select-corporation'
});
} else {
next({
path: '/branches'
});
}
});
export default router;
检查您的目标路由是否 select-corporation
以中断无限重定向循环,如果已经选择公司,"else" 块也会导致相同的行为:
router.beforeEach((to, from, next) => {
if (localStorage.getItem('selectedCorporation') === null) {
// checking to avoid loop
if (to.name === 'corporations.select') return next();
next({
path: '/select-corporation'
});
}
else {
next();
}
});
如果您想在选择公司后将用户重定向到 branches
页面,只需在 CorporationsSelect
中执行即可。