首页 > 解决方案 > vue-router beforeEach 导航守卫错误:

问题描述

我有一个与这个 stackoverflow question类似的问题,但是那里提到的所有解决方案都对我不起作用。我的情况有什么不同?

我在“团队”页面上。在我的应用程序中单击导航栏中的链接时,router.push({name: "polls"})调用 then 以导航到“投票”页面。但是我得到了错误,那个导航被取消了。为什么?

错误信息

Uncaught (in promise) Error: Navigation cancelled from "/team" to "/polls" with a new navigation.
    at createRouterError (vue-router.esm.js:2065)
    at createNavigationCancelledError (vue-router.esm.js:2047)
    at vue-router.esm.js:2394
    at step (vue-router.esm.js:2001)
    at step (vue-router.esm.js:2008)
    at runQueue (vue-router.esm.js:2012)

我有一个相当复杂的beforeEach()路线导航守卫:

    router.beforeEach((routeTo, routeFrom, next) => {
        //Keep in mind that next() must exactly be called once in this method.
        console.log("beforeEach ENTER", routeFrom.path, "=>", routeTo.path)
        tryToAuthenticate().then(() => {
            log.debug("vue-router: authenticated", routeFrom.path, "=>", routeTo.path)
            if (routeTo.path === "/" || routeTo.path === "/index.html") {
                next({name: "teamHome"})
            } else {
                next()
            }
        }).catch(() => {
            log.debug("vue-router: anonymous", routeFrom.path, "=>", routeTo.path)
            if (routeTo.meta.public) {
                next()
            } else if (routeTo.path === "/" || routeTo.path === "/index.html") {
                next({name: "welcome"})
            }   else {      
                next({name: "login"})
            }
        })
    })

tryToAuthenticated()当用户已经通过身份验证并且 JWT 存储在 localStorage 中时,该方法返回一个承诺。情况就是这样。在我的测试用例中,用户已登录。

即使我删除了所有这些,并且只next()在 beforeEach Hook 中放置了一个默认调用,我仍然得到同样的错误。

我在其他问题中尝试了所有建议的解决方案:

调试

此方法中出现错误vue-router.esm.js

    runQueue(queue, iterator, function () {
        // wait until async components are resolved before
        // extracting in-component enter guards
        var enterGuards = extractEnterGuards(activated);
        var queue = enterGuards.concat(this$1.router.resolveHooks);
        runQueue(queue, iterator, function () {   
          if (this$1.pending !== route) {           // <=================================
            return abort(createNavigationCancelledError(current, route))
          }
          this$1.pending = null;
          onComplete(route);

this$1.pending仍然具有页面(“团队”)的值,并且路由指向我要导航到的页面(“民意调查”)。为什么还有东西待处理????


Ok 似乎与动态/异步组件有关。我的投票页面是一个异步组件。替换为正常导入的组件,然后它就可以工作了。看起来像 vue-router 的异步行为中的错误

标签: vue-router

解决方案


推荐阅读