vue路由报错NavigationDuplicated

2,467 阅读1分钟

(看到别人说的一种方法,路由版本降到3.0.7,没亲测过,不推荐 )

1、具体报错:NavigationDuplicated: Avoided redundant navigation to current location: "/sub/mountStep"

2、原因:即将加载的路由与当前路由重复

3、解决办法:重写路由的push方法,隐藏报错

const routerPush = VueRouter.prototype.push
console.log("old-routerPush", routerPush)
VueRouter.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error=> console.log("error",error))
}

4、说明:为什么要这么写?这样写的目的只是让这个报错消失而已,其实报错还存在

4.1、先看文档说明

4.2、再看一下vue-router内部的原有push方法

VueRouter.prototype.push = function push (location, onComplete, onAbort) {
    var this$1 = this;
  // $flow-disable-line
  if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
    return new Promise(function (resolve, reject) {
      this$1.history.push(location, resolve, reject);
    })
  } else {
    this.history.push(location, onComplete, onAbort);
  }
};

vue-router3.1.0之后的路由的push方法调用会返回一个promise对象

Promise.prototype.catch方法:捕捉错误

5、总结:到这里基本就明白了,routerPush.call(this, location).catch()就是重写后的push仍然调用原来的push方法,只不过多加了一个catch()处理报错