vue-router.esm.js:2054 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/operation/permission?tab=roles”
这个错误 NavigationDuplicated: Avoided redundant navigation to current location 是 vue-router 的一个经典问题。
原因分析:
Vue Router 3.x 版本中,当调用 this.router.push或this.router.push 或 this.router.push或this.router.replace 跳转到当前路由时,会抛出一个 NavigationDuplicated 错误。如果调用处没有 .catch() 处理,就会报 Uncaught (in promise)。
处理方式:
通过重写 Router.prototype.push 和 Router.prototype.replace,捕获该特定错误并忽略它,同时保留其他真实错误的抛出。
位置:
将上述代码放在 export default new Router(…) 之前即可生效。
代码:
const originalPush = Router.prototype.push Router.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => { if (err.name !== 'NavigationDuplicated') { throw err } }) } const originalReplace = Router.prototype.replace Router.prototype.replace = function replace(location) { return originalReplace.call(this, location).catch(err => { if (err.name !== 'NavigationDuplicated') { throw err } }) }