vue-router - 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 中放置了一个默认调用,我仍然得到同样的错误。
我在其他问题中尝试了所有建议的解决方案:
- 捕获返回的错误:
router.push('/polls').catch(() => {});
=> 这会捕获错误,但页面仍然没有切换到预期的目标页面“轮询”。 - 将 router.push 替换为
<router-link :to="{name: 'polls'}">
有效的 - FunFact:单击按钮两次也可以第二次工作。
调试
此方法中出现错误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 的异步行为中的错误
解决方案
推荐阅读
- c# - ASP.NET 将 .doc 转换为 .pdf 相对路径映射失败
- c++ - C中负数的逻辑与运算符
- amazon-web-services - AWS IAM 资源策略 - 密钥管理器中的 NotPrincipal 资源策略问题
- python - Multi_plane_detection 代码中的 AttributeError
- javascript - 如何在反应中将子组件的状态数组传递给父组件?
- python - 如何仅在某些工作日分组?
- javascript - 随机对象内的 JavaScript 随机对象
- dependencies - Cloud Run 容器可能由于包问题而无法构建?
- mongodb - Mongodb更新管道更新嵌套数组中元素的字段
- javascript - 如何通过 Javascript 显示 chrome 的日期选择器