美文网首页
Vue-router 使用编程式导航多次执行会报错Navigat

Vue-router 使用编程式导航多次执行会报错Navigat

作者: 扶得一人醉如苏沐晨 | 来源:发表于2023-03-11 17:49 被阅读0次

一、路由跳转有以下两种方式:

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

二、问题

编程式路由跳转到当前路由(参数不变),多次执行会抛出NavigationDuplicated的警告错误?
声明式导航没有此类错误,因为 vue-rourer底层已经处理好了

image.png

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

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

三、解决

3.1、方式一

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

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

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

3.1、方式二

通过底层的代码,可以解决这个错误
通过重写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,
      () => {},
      () => {}
    );
  }
};

相关文章

网友评论

      本文标题:Vue-router 使用编程式导航多次执行会报错Navigat

      本文链接:https://www.haomeiwen.com/subject/zmkoldtx.html