关于连续点击路由跳转控制台报错问题?

220 阅读1分钟

要问程序员最害怕的是什么,当属是控制台红色预警了! 你们可曾见过如下代码吗?

image.png

"Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: /search/%E5%8D%8E%E4%B8%BA"
(未捕获(承诺中)导航重复:避免了对当前位置的冗余导航:)

为此我找到了两种可以解决以上报错问题的方式,如有不足之处还请补充

需要在router.js文件中配置!!!一定注意不是在main.js中添加这些代码

方式一:重写push和replace方法(推荐使用)

//我们首先把VueRouter原型上的push方法保存一份以防后期用到时丢失
let originPush = VueRouter.prototype.push;

//重定义location跳转到哪里,resolve:成功的回调,reject:失败的回调
 VueRouter.prototype.push = function (location, resolve, reject) {
     if (resolve && reject) {
         originPush.call(this, location, resolve, reject);
     } else {
         originPush.call(this, location, () => { }, () => { })
     }
 }
 
  let originReplace = VueRouter.prototype.replace;

 VueRouter.prototype.replace = function (location, resolve, reject) {
     if (resolve && reject) {
         originReplace.call(this, location, resolve, reject)
     } else {
         originReplace.call(this, location, () => { }, () => { })
     }
 }
 

##方式二:直接在push方法最后添加异常捕获 (捕捉错误提示但不显示)

@click="$router.push('/home/searchPopup').catch(err=>{})"