重写VueRouter的push|replace

重写VueRouter的push|replace

文章目录


前言

在进行编程式路由导航的时候,反复点击控制台就会提示报错,为了深入了解编程式路由跳转,以及

防止控制台的多次报错需要对VueRouter的原型上的push以及replace进行重新编写!


编写

找到router/index.js文件,也就是路由的入口文件

先将原型的push|replace保存一份:

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

在后方编写其他内容:

// 重写push|replace
// 第一个参数:需要跳转的地址(传递哪些参数)
// 第二个参数:成功的回调
// 第三个参数:失败的回调
VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

复制内容,把replace重写一遍:

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

// 重写push|replace
// 第一个参数:需要跳转的地址(传递哪些参数)
// 第二个参数:成功的回调
// 第三个参数:失败的回调
VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej)
  } else {
    originPush.call(this,location,() => {},() => {})
  }
}
// 重写push|replace
// 第一个参数:需要跳转的地址(传递哪些参数)
// 第二个参数:成功的回调
// 第三个参数:失败的回调
VueRouter.prototype.replace= function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej)
  } else {
    originReplace.call(this,location,() => {},() => {})
  }
}

总结

例如:以上就是今天要讲的内容,本文仅仅简单介绍了重写VueRouter的push|replace,vue-router的

底层是使用promise的,所以需要指明成功和失败的回调

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值