报错内容:
vue-router.esm.js?68cf:2065 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/search".
at createRouterError (webpack-internal:///./node_modules/[email protected]@vue-router/dist/vue-router.esm.js:1993:15)
at createNavigationDuplicatedError (webpack-internal:///./node_modules/[email protected]@vue-router/dist/vue-router.esm.js:1978:15)
报错图片:
出现报错原因:使用编程式路由实现跳转的时候,多次执行会抛出NavigationDuplicated的警告错误是因为"vue-router"3版本之后 底层引入了promise,而通过声明式导航没有出现此类问题是因为vue-router底层已经处理好了。
解决方法1:在router文件夹下的index.js下添加如下内容
// 解决vue-router在3.0版本以上重复点报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
解决方法2:在router文件夹下的index.js下:
let originPush=VueRouter.prototype.push;
let originReplace=VueRouter.prototype.replace;
//重写push/replace
//第一个参数:告诉原来的push方法,往哪里跳转(传递哪些参数)
//第二个参数:成功的回调
//第三个参数:失败的回调
//call/apply区别
//相同点:都可以调用函数一次,都可以篡改函数的上下文(this)一次‘
//不同点: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,()=>{},()=>{});
}
}
let originPush=VueRouter.prototype.push;
let originReplace=VueRouter.prototype.replace;
//重写push/replace
//第一个参数:告诉原来的push方法,往哪里跳转(传递哪些参数)
//第二个参数:成功的回调
//第三个参数:失败的回调
//call/apply区别
//相同点:都可以调用函数一次,都可以篡改函数的上下文(this)一次‘
//不同点: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,()=>{},()=>{});
}
}