注意:编程式导航(push|replace)才会有这种情况的异常,声明式导航是没有这种问题,因为声明式导航内部(vue-router)已经解决这种问题。
首先请明确一点,
这种异常,对于程序运行是没有任何影响的。
但是看着非常烦
为什么会出现这种现象:
由于 vue-router 最新版本 3.5.2,引入了 promise,当传递参数多次且重复,会抛出异常,因此出现上面现象,
function push(){
return new Promise((resolve,reject)=>{})}
第一种解决方案(仅解决当前函数):是给 push 函数,传入相应的成功的回调与失败的回调
this.$router.push({
name: "search",
params: { keyword: this.toSearchKeyword || undefined },
query: { k: this.toSearchKeyword } ,
()=>{},//成功的回调
(error)=>{console.log(error)},//失败的回调
});
第一种解决方案可以暂时解决当前问题,但是以后再用 push / replace 还是会出现类似现象,因此我们需要从‘根’治病;
第二种解决方案(推荐): 重写 push/replace
当你传入resolve和reject时,值为undefined,解析为true,则正常使用
当你没传入resolve和reject时,值为undefined,解析为false,则使用我们自己写的空回调
把这些配置在router里,就可以解决报错
但是注意,这样会不能传输路由元数据
//把VueRouter原型对象的push方法保存一份
let originPush = VueRouter.prototype.push;
//把VueRouter原型对象的replace方法保存一份
let originReplace = VueRouter.prototype.replace;
//重写push
//location:告诉原来push方法,你往哪里跳转(传递哪些参数)
//resolve:成功的回调
//reject:失败时的回调
VueRouter.prototype.push = function (location, resolve, reject) {
if (resolve && reject) {
originPush.call(this, location, resolve, reject);
} else {
originPush.call(
this,
location,
() => {},
() => {}
);
}
};
//重写replace
VueRouter.prototype.replacce = function (location, resolve, reject) {
if (resolve && reject) {
originReplace.call(this, location, resolve, reject);
} else {
originReplace.call(
this,
location,
() => {},
() => {}
);
}
};
恭喜你获得干净的控制台~
另外备注:
//calll || apply区别
//相同点,都可以调用函数一次,都可以篡改函数的上下文一次
//不同点: call与apply传递参数: call传递参数用逗号隔开,apply方法执行,传递数组