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