编程式导航(重写VueRouter.push|replace)

问题:编程式导航路由跳转到当前路由(参数不变), 多次执行会抛出NavigationDuplicated的警告错误?

注意:编程式导航(push|replace)才会有这种情况的异常,声明式导航是没有这种问题,因为声明式导航内部已经解决这种问题。

 

这种异常,对于程序运行没有任何影响。

为什么会出现这种现象:

由于vue-router最新版本3.5.2,引入了promise,push、replace方法会返回一个Promise。当传递参数多次且重复,或是没有写成功或失败的回调。会抛出异常,因此出现上面现象

=======================================================================

第一种解决方案:是手动给push和replace方法,传入相应的成功的回调与失败的回调

this.$router.push({name:"search",params:{keyword:this.keyword},query:{this.keyword.toUpperCase()}},()=>{},()=>{})

第一种解决方案可以暂时解决当前问题,治标不治本,但是以后再用push|replace还是会出现类似现象,因此我们需要从‘根’治病;

=======================================================================

第二种解决方案:重写$router的push和replace方法

首先我们要清楚,在组件中:

this:表示当前组件实例对象(search组件,实质是Vuecomponent实例对象)

this.$router属性:表示的是VueRouter的一个实例。在入口文件main.js注册路由时,给每个组件身上都加了$route|$router属性

this.$router.push()方法:实际上是VueRouter这个构造函数的原型对象身上的方法(即VueRouter.prototype的方法)

我们使用this.$router.push()方法时,方法内部代码执行的上下文为VueRouter的一个实例(即用this.$router.push()和VueRouter.prototype.push()时,函数体内的this均指向VueRouter的一个实例,故重写push|replace方法时需要将this重新指向VueRouter实例)

//引入vue-router路由插件
import VueRouter from "vue-router";
//引入Vue
import Vue from "vue";
import routes from "./routes";
//使用插件
Vue.use(VueRouter);
//需要重写VueRouter.prototype原型对象身上的push|replace方法
//先把VueRouter.prototype身上的push|replace方法进行保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

 

//重写VueRouter.prototype身上的push方法了
VueRouter.prototype.push = function(location, resolve, reject) {
  //第一个形参:路由跳转的配置对象(query|params)
  //第二个参数:undefined|箭头函数(成功的回调)
  //第三个参数:undefined|箭头函数(失败的回调)
  if (resolve && reject) {
    //push方法传递第二个参数|第三个参数(箭头函数)
    //originPush:利用call修改上下文,变为(路由组件.$router)这个对象,第二参数:配置对象、第三、第四个参数:成功和失败回调函数
    originPush.call(this, location, resolve, reject);
  } else {
    //push方法没有产地第二个参数|第三个参数
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

 

//重写VueRouter.prototype身上的replace方法了
VueRouter.prototype.replace = function(location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

 

//对外暴露VueRouter类的实例
let router = new VueRouter({
  routes,
});
export default router;

 

posted @ 2023-05-15 08:48  GLin生活派  阅读(184)  评论(0)    收藏  举报