解决vue-router的编程式路由导航的NavigationDuplicated

213 阅读2分钟

--问题描述:当我点击搜索框进行商品搜索的时候,采用编程式路由导航有警告NavigationDuplicated --问题原因:由于路由没有重写push和replace方法导致 --解决办法:可以通过给push和replace传递成功和失败的回调函数来解决,也就是需要在原有项目中重写push和replace方法 --代码注释: //  2022/04/05 处理search的适合反复点击"搜索按钮报错的问题"

// 2022/02/08 面试题:call和apply的区别:相同点->都可以调用函数

// 不同点:call和apply传递参数:call传递参数用逗号隔开;apply方法执行传递数组.

// js基础:call(),apply(),bind()都是用来绑定this的

// 需要重写VueRouter.prototype原型对象身上的push|replace方法

// 先把VueRouter.prototype身上的push|replace方法进行保存一份

let originPush = VueRouter.prototype.push;

let originReplace = VueRouter.prototype.replace;

// 重写VueRouter.prototype身上的push方法了,利用promise   2022/03/31

VueRouter.prototype.push = function (location, resolve, reject) {

  // 第一个形参:路由跳转的配置对象(query|params)

  // 第二个参数:undefined|箭头函数(成功的回调)

  // 第三个参数: undefined|箭头函数(失败的回调)

  // 如果传递了resolve和reject两个回调函数则用原来的push()方法

  if (resolve && reject) {

    // push原来是挂载在window上的,因此通过call去改变this的指向

    // push方法传递第二个参数|第三个参数(箭头函数)

    // originPush:利用 call 修改上下文,变为(路由组件.$router)这个对象,第二参数:配置对象、第三、第四个参数:成功和失败回调函数

    originPush.call(this, location, resolve, reject);

  } else {

    // 如果没有传递resolve和reject两个回调函数则在原来push的回调上手动传入两个回调函数.

    //push方法没有产地第二个参数|第三个参数

    originPush.call(

      this,

      location,

      // 手动传入两个回调

      () => { },

      () => { }

    );

  }

};

//重写VueRouter.prototype身上的replace方法了,2022/01/12已经学过了vue2中route中的replace方法了

VueRouter.prototype.replace = function (location, resolve, reject) {

  if (resolve && reject) {

    originReplace.call(this, location, resolve, reject);

  } else {

    originReplace.call(

      this,

      location,

      () => { },

      () => { }

    );

  }

};