提示错误代码:Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/search/dd?".
at createRouterError (webpack-internal:///./node_modules/_vue-router@3.6.5@vue-router/dist/vue-router.esm.js:1714:15)
注意:编程式路由跳转(push | replace),才会出现这种异常情况,声明式路由不会有此情况,因为vue-router导航内部已经解决了。
说明:这只是警告,对程序运行没有影响、
但是看着就烦
为什么会出现这种情况呢? 因为this.$router.push() 返回的是一个promise函数,缺少了对promise成功&失败的回调,
function push(){
return new Promise((resolve,reject)=>{})}
解决方案一:
this.$router.push({
name:'search',
params:{keyword:this.keyword ||undefined},
}).then(()=>{}).catch(()=>{})//捕获成功和失败的数据
但是一般不这样写,因为push第二个成功的回调,第三个参数是失败的回调
解决方案二:
//push 第一个参数是跳转路径和参数
//push 第二个参数是成功的回调
//push 第三个参数是失败的回调
this.$router.push({
name:'search',
params:{keyword:this.keyword ||undefined},
},()=>{},()=>{})
每次使用push | replace 都需要参数回调,指标不治本。因此要修改push底层源码
解决方案三:
在router/index.js页面中,修改VueRouter.prototype.push方法,添加成功回调与失败回调
//先把VueRouter原型对象上的push|,先保存一份
let originPush=VueRouter.prototype.push;
let originReplace=VueRouter.prototype.replace;
//重写push | replace 方法
//第一个参数:location,要往哪里跳、传递参数
//第二个参数:成功的回调
//第三个参数:失败的回调
VueRouter.prototype.push = function(location,res,rej){
if(res&&rej){
originPush.call(this,location,res,rej)
}else{
originPush.call(this,location,()=>{},()=>{})
}}
VueRouter.prototype.replace = function(location,res,rej){
if(res&&rej){
originReplace.call(this,location,res,rej)
}else{
originReplace.call(this,location,()=>{},()=>{})
}}
ok,解决了~