前情提要
今天做个人项目时遇到个第一次见的报错,是 vue-router 的报错,如下
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/trash?noteId=5004".
报错原因
最新的 vue-router 引入了 promise
提示路由重复跳转
比如我现在报错的代码:当前的路由是 /trash,但后续我还有 this.$router.replace 的操作,路由依旧是 /trash,这样 vue-router 就会在控制台报路由重复的错误。
这个错误不会影响项目的运行和页面效果,只是会在控制台报错
解决方法
思路:修改 VueRouter 原型对象上相对应的方法
原理:修改原型对象上的方法,增加了对抛出的错误进行捕获的操作,捕获到错误后不做任何操作。(不做任何操作也不会对重复跳转的组件有任何的影响,也不会对要跳转的组件进行重新渲染,因为他并不会执行重复跳转的操作)
具体代码
使用 this.$router.replace 更新路由时
// 在 src/router/index.js 中新增如下代码
import Router from 'vue-router';
Vue.use(Router)
const originalReplace = Router.prototype.replace
Router.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
}
使用 this.$router.push 更新路由时
// 在 src/router/index.js 中新增如下代码
import Router from 'vue-router'
Vue.use(Router)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
添加完代码后再刷新页面查看控制台,报错消失。
补充
后来又遇到以下报错
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_normalized')
一样是用上面的重写 vue-router 的方法来解决,所以遇到此类报错最稳妥的方法就是把项目里用到的 vue-router 上的方法都重写一次捕捉错误(前提是这个错误不会导致项目出 bug,一般只要重写 push 和 replace 即可,用的比较多)