【vue报错】:vue-router.esm.js a12b:2046 Uncaught (in promise) NavigationDuplicated:A

253 阅读1分钟

报错:

vue-router.esm.js?a12b:2046 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/homeauto".

报错原因:

重复点击当前的路由,因为当前vue-router引入了promise,当我们使用this.$router.push时候需要都添加成功或失败的回调,否则就会报出以上的错误。 在这里插入图片描述 在这里插入图片描述

解决办法

第一种

switchTab(path) {
   if (this.$router.path == path) return
   this.$router.push(path)
}

第二种

跳转后使用catch语句对错误不再进行处理

this.$router.push(path).catch(err => {})

第三种

基于第二种方法,当我们的路由跳转过多时就需要每次跳转都要加上catch回调,这样比较麻烦,所以还可以在引入vueRouter文件下重写push和replace方法

import VueRouter from 'vue-router';
//保存原型对象的Push
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
//重写push方法
VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej)
  }
  else {
    originPush.call(this, location, () => { }, () => { })
  }
 
}
//重写replace方法
VueRouter.prototype.replace = function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej)
  }
  else {
    originReplace.call(this, location, () => { }, () => { })
  }
}