vue-router.esm.js:2046 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to c

vue-router.esm.js:2046 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/search”.
在这里插入图片描述
报错原因:重复点击路由导致,因为vue-router引入了promise,当我们使用this.$router.push时候需要多添加成功或失败的回调,否则就会报出以上的错误。
源代码:
在这里插入图片描述
解决办法:
第一种方法:跳转后使用catch语句对错误不再进行处理

	this.$router.push('./search').catch(err => {})

第二种方法:
在进行路由跳转时对路径进行判断如果重复即不再执行

// 搜索按钮的回调函数:需要向search路由进行跳转
        goSearch(){
            // 注意这里是this.$route,拿到当前路由 
            // path为'/search',并非'./search'
            if(this.$route.path == '/search') return 
            console.log(this.$route.path );
            this.$router.push('/search')
        }

第三种方法,在路由组件内,修改VueRouter原型对象上的push和replace方法

let originPush = VueRouter.prototype.push  // 备份一下VueRouter原型对象的方法
let originReplace = VueRouter.prototype.replace
// 重写push|replace
// 第一个参数,告诉原来的push方法,你往哪里跳转,传递那些参数
// 第二个参数:成功的回调
// 第三个参数:失败的回调
// call || apply区别:
// 相同点:都可以调用函数一次,都可以篡改函数的上下文一次
// 不同点: call与apply传递参数,call传递参数用逗号隔开,apply方法执行,传递数组
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, () => { }, () => { })
    }
}
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值