Vue-router 使用编程式导航多次执行会报错NavigationDuplicated的解决方法

路由跳转有以下两种方式:
1.声明式导航: router-link,需要to属性,可以实现路由的跳转
2.编程式导航: 利用的是组件的实例 $route.push|replace 方法,可以实现路由的跳转

编程式导航跳转到当前路由时,多次执行会抛出 NavigationDuplicated的警告错误。
在这里插入图片描述
声明式导航没有此类错误,因为 vue-rourer底层已经处理好了

为什么编程式导航进行路由跳转的时候,就有这种警告错误呢?

“vue-router”: “^3.5.3”: 最新版的vue-router 引入promise,而push函数没有传入 成功和失败的函数

怎么解决呢
1.通过给push方法传递相应的成功、失败的回调函数,可以捕获到当前错误,可以解决。

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

这种写法: 治标不治本,将来在别的组件当中push|replace, 编程式导航还是有类似错误。

2.通过底层的代码,可以解决这个错误

通过重写VueRouter.prototype身上的replace和push方法来解决上面的异常。

//先把VueRouter原型对象的push,先保存一份
let originPush = VueRouter.prototype.push;

//第一个参数: 告诉原来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,
      () => {
    
    },
      () => {
    
    }
    );
  }
};

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/124483447#comments_22134739