参考链接:
https://www.jb51.net/article/280106.htm
https://blog.csdn.net/misschengispink/article/details/122058267
https://blog.csdn.net/weixin_43263566/article/details/127113293
解决方法:
在vue的路由route文件夹下的index.js,写以下代码
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
// 解决跳转到当前路由报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
以下内容来自于尚硅谷视频中
问题:编程式路由跳转到当前路由(参数不变),多次执行会抛出NavigationDuplicated的警告错误?
路由跳转有良种方式:声明式导航、编程式导航。
声明式导航没有这类问题,因为vue-router底层已经处理好了。
问题:为什么编程式导航进行路由跳转时候,就会有这种警告错误呢?
最新的vue-router引入promise。
通过给push方法传递相应的成功、失败的回调函数,可以捕获到当前错误,可以解决。
通过底部的代码,可以实现解决错误:this.$router.push({name: ‘search’,}, ()=>{}, () => {})。
// 在router文件中,写如下代码,即可解决
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
// 先把VueRouter原型对象的push方法,先保存一份
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
// 重写push|replace
// 第一个参数:告诉原来push方法,你要往哪里跳转(也就是要传递哪些参数)
// 第二个参数:成功回调
// 第三个参数:失败回调
VueRouter.prototype.push = function (location, resolve, reject) {
if (resolve && reject) {
originalPush.call(this, location, resolve, reject);
} else {
originalPush.call(this, location, () => { }, () => { });
}
};
VueRouter.prototype.replace = function (location, resolve, reject) {
if (resolve && reject) {
originalReplace.call(this, location, resolve, reject);
} else {
originalReplace.call(this, location, () => { }, () => { });
}
};