一、原因
路由跳转有两种形式:
- 声明式:
<router-link :to="...">
- 编程式:
router.push(...)
声明式导航是没有这种问题的,这是因为 vue-router 底层已经处理好了。
而编程式导航连续点击进行路由跳转的时候,就会在控制台抛出 Uncaught (in promise) NavigationDuplicated 错误信息,错误信息如下:
这是因为 vue-router 版本升级到了 v3.1.0 之后,push 和 replace 方法会返回一个 promise,如果没有对错误进行捕获,那么控制台就会输出未捕获异常。
2 解决方法(四种方法)
方法一:使用时对错误进行捕获。
this.$router.push('home').catch(err => { return err })
方法二: 使用时给 push 传递相应的成功、失败的回调函数。
this.$router.push({ path: 'home' }, () => {}, () => {})
方法三:降低 vue-router 版本为 3.0。
npm install vue-router@3.0
方法四:重写 push 和 replace 方法,只需要在 router 文件夹下的 index.js 文件里面加入如下代码即可。(我项目上也是使用这种方法)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
return originalReplace.call(this, location).catch(err => err)
}