重写push()和replace()

635 阅读1分钟

遇到的问题

在vue中我们使用编程式导航时,当我们多次点击跳转时,会报以下错误:

image.png 因此为了解决这个问题,我们需要在push()中传入处理resolve和reject这连个回调函数。

但是为了以后使用的方便,这次我们采用重写push()和replace()方法。

分析问题

      this.$router.push({
        name: "search",
        params: { Pkey: this.value },
        query: { Qkey: this.value.toUpperCase() },
      });
      console.log(this.$router);
    },

this.routerVueRouter的实例,this.router是VueRouter的实例,this.router上不存在push()

image.png

image.png

push()方法是在VueRouter的原型对象上的,因此我们需要重写VueRouter.prototype.push方法

VueRouter就是我们配置路由的地方的那个VueRouter对象,因此我们可以在router.js中重写这两个方法

//保存原始的push和replace
const originalpush = vueRouter.prototype.push;
const originalreplace = vueRouter.prototype.replace;

vueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originalpush.call(this, location, resolve, reject);
  } else {
    originalpush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
vueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originalreplace.call(this, location, resolve, reject);
  } else {
    originalreplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

注意:重写的函数不能使用箭头函数,因为箭头函数没有隐式绑定this的功能,并且我们需要使用call方法来调用原始的方法,保证this的正确性。