【问题标题】:Maximum Call Stack Exceed Using Vue Js Router使用 Vue Js 路由器超过最大调用堆栈
【发布时间】:2019-04-27 08:36:26
【问题描述】:

我和这里的其他人一样有共同的问题,我尝试遵循他们的解决方案,但我仍然无法解决。在我的应用程序中,我需要先登录,然后选择公司,然后再进入主页。我的登录没有问题,我的问题出在选定的公司上。如果他们没有选择公司,我需要附加一个可以阻止他们访问主页的警卫。我所做的是检查本地存储,如果 selectCorporation 为空,那么我将能够知道他们选择了一家公司。

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,即使目标路由本身是select-corporation。所以这是无限重定向循环。
  • @MaxSinev。是的,我相信这就是问题所在。那么我该如何解决这个问题,我已经设置了 else 条件?谢谢

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

检查您的目标路由不是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 中执行此操作即可。

【讨论】:

  • 感谢您的回答。但仍然是同样的错误。超出最大调用堆栈
  • @Joseph 你在公司路线路径的开头错过了/,添加并重试。
  • 我稍微更新了我的答案代码。您可以查看我创建的这个 jsfiddle 来测试您的问题 jsfiddle.net/3px84r2b 没有错误...
  • 我明白了。非常感谢。祝你有美好的一天
  • 当我在 selectedCorporation 为空时尝试单击其他按钮时,就会出现最大调用堆栈。知道如何解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2018-07-11
  • 2019-09-04
  • 2017-01-14
  • 2017-03-01
  • 2017-05-23
相关资源
最近更新 更多