Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/?k=“

出现这个警告

编程式路由跳转到当前路由,(参数不变),多次点击执行抛出如上图异常,声明式导航没有这个警告,Vue-router底层已经处理好了

问题产生的原因

'vue-router':"^3.5.3":最新的vue-router引入了promise

解决方案:

1,通过给push或者replace方法传递响应的成功、失败的回调函数,可以捕捉到当前警告,既可以解决,这种方法治标不治本,换个组件(其他组件用的push方法)又得在push中添加失败和成功的回调.

 this.$router.push({name:'search',params:{keyword:this.keyword},query:{k:this.keyword.toUpperCase()}},()=>{},(error)=>{
  // console.log(this.$router)   //传入成功或失败的回调解决(捕获)这个异常的问题
 })

2.修改底层的源码,重写$router.push与$router.replace方法(治本)

首先要明白:    $router是VueRouter的一个实例  push是VueRouter原型上的方法.

//先把VueRouter原型对象的push,先保存一份

let originPush = VueRouter.prototype.push;

let originReplace = VueRouter.prototype.replace;

//console.log(originPush);

//重写push|replace

//第一个参数,告诉原来的push方法,你往哪里跳(传递哪些参数)

VueRouter.prototype.push = function (location, resolve, reject) {

    //console.log(this);

    if (resolve && reject) {

        //  otiginPush();  //originPush的上下文是windows

        //call||apply区别:相同点,都可以调用函数一次,都可以篡改函数的上下文一次

        //不同点:call与apply传递参数:call传递参数用逗号隔开,apply方法执行m传递数组

        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,()=>{},()=>{});

       }

}

 在index.js中重写push|replace

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值