关于产生冗余导航,vue-router报错的问题

司徒耀
2023-12-01

项目场景:

写编程式路由导航时,vue-router报错。


问题描述:

Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/home/message/detail?id=003&title=%E6%B6%88%E6%81%AF003".
    at createRouterError (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:2066:15)
    at createNavigationDuplicatedError (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:2036:15)
    at HashHistory.confirmTransition (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:2329:18)
    at HashHistory.transitionTo (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:2261:8)
    at HashHistory.push (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:2711:10)
    at eval (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:3027:22)
    at new Promise (<anonymous>)
    at VueRouter.push (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:3026:12)
    at VueComponent.pushShow (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/pages/Message.vue?vue&type=script&lang=js&:49:20)
    at click (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"6e0dfc24-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/pages/Message.vue?vue&type=template&id=3b897f93&:38:34)
createRouterError @ vue-router.esm.js?8c4f:2065
createNavigationDuplicatedError @ vue-router.esm.js?8c4f:2035
confirmTransition @ vue-router.esm.js?8c4f:2328
transitionTo @ vue-router.esm.js?8c4f:2260
push @ vue-router.esm.js?8c4f:2710
eval @ vue-router.esm.js?8c4f:3026
push @ vue-router.esm.js?8c4f:3025
pushShow @ Message.vue?e8c4:38
click @ Message.vue?6cd7:35
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961

原因分析:

按钮多次在一个页面跳转,产生冗余导航。


解决方案:

将下面的代码放入main.js或index.js文件中即可。

import VueRouter from 'vue-router'
// 解决同一页面产生导航冗余,vue-router报错问题
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
 类似资料: