使用编程式导航路由跳转到当前路由(参数不变), 多次执行会抛出NavigationDuplicated的警告错误
注意:编程式导航(push|replace)才会有这种情况的异常,声明式导航是没有这种问题,因为声明式导航内部已经解决这种问题
为什么会出现这种现象:
由于vue-router最新版本3.5.2,引入了promise,当传递参数多次且重复,会抛出异常,因此出现上面现象,
第一种解决方案:将vue-router降低到4的版本
npm install vue-router@4
第二种解决方案:是给push函数,传入相应的成功的回调与失败的回调
const result= this.$router.push({name:'search', params: {keyword: this.value}}.() => {}, () => {})
// 返回值是 Promise {}
// 第一个是成功时的回调,第二个是失败时的回调
第二种解决方案可以暂时解决当前问题,但是以后再用push|replace还是会出现类似现象,因此我们需要从‘根’治病
为什么这里要用到call呢?
因为originPush的this不是VueRouter的实例,所以需要用到call修改其this的指向
重写push方法:
// 需要重写VueRouter.prototype原型对象身上的push方法
//先把VueRouter.prototype身上的push方法进行保存一份
let originPush = VueRouter.prototype.push;
//重写VueRouter.prototype身上的push方法了
VueRouter.prototype.push = function(location, resolve, reject) {
//第一个形参:路由跳转的配置对象(query|params)
//第二个参数:undefined|箭头函数(成功的回调)
//第三个参数:undefined|箭头函数(失败的回调)
if (resolve && reject) {
//push方法传递第二个参数|第三个参数(箭头函数)
//originPush:利用call修改上下文,变为(路由组件.$router)这个对象,
// 第二参数:配置对象、第三、第四个参数:成功和失败回调函数
originPush.call(this, location, resolve, reject);
} else {
//push方法没有产地第二个参数|第三个参数
originPush.call(
this,
location,
() => {},
() => {}
);
}
};