路由跳转报错(NavigationDuplicated: Avoided redundant navigation to current location: )

987 阅读1分钟

在写代码时,当前路由跳转到当前路由会报错,提示 NavigationDuplicated: Avoided redundant navigation to current location: "/nav". 意思是路由导航冗余,重复了

image.png

看了网友的解决方案是在router文件中加入一下代码

Vue.use(VueRouter)

//添加以下代码
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = []

然后仔细去找了下报错的原因,跳转的push方法会有一个返回promise函数, 如果报错不处理就会被全局路由处理在浏览器上提示。

//源码中push方法
 push (location: RawLocation, location?: Function, onAbort?: Function) {
    // $flow-disable-line
    if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
      return new Promise((resolve, reject) => {
        this.history.push(location, resolve, reject)
      })
    } else {
      this.history.push(location, onComplete, onAbort)
    }
  }

其他解决方法

// 在push后面处理报错信息
this.$router.push(path)
    .catch(err=> err)