编程式导航报错的解决
当没有输入新数据并且连续点击Header组件中的Search按钮时会产生如下报错。编程式导航(push|replace)才会有这种情况的异常,声明式导航是没有这种问题,因为声明式导航内部已经解决这种问题。这种异常,对于程序没有任何影响的。
该错误出现的原因为:由于vue-router最新版本3.5.2,引入了promise,当传递参数多次且重复,会抛出异常,因此出现上面现象。
这种报错不会影响项目的使用,但是会影响程序员的心态,为了一劳永逸的解决这种报错,首先找到配置路由的index.js文件。在里面对Vuerouter的原型方法push方法与replace进行重写。
重写代码如下,可以直接复制使用
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写push||replace
//第一个参数:告诉原来的方法往哪里跳转,第二个参数成功回调,第三个参数失败回调
VueRouter.prototype.push = function (location, resolve, reject) {
if (resolve && reject) {
originPush.call(this, location, resolve, reject)
} else {
originPush.call(this, location, () => { }, () => { })
}
}
VueRouter.prototype.replace=function(location,resolve,reject){
if(resolve && reject){
originReplace.call(this, location, resolve, reject)
}else{
originReplace.call(this, location, () => { }, () => { })
}
}