Vue中使用[$router.push]重复点击报错解决方案

本文讨论了在使用Vue Router时遇到的重复点击$router.push()或$router.replace()导致的错误。该错误是由于防止组件重复渲染而抛出的。解决方法包括在调用$router.push()时添加catch处理,或者全局重写VueRouter的push和replace方法以捕获并忽略错误。这两种方案都可以有效地避免错误显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        $router.push()或者$router.replace 重复点击的时候会报错,这个错误老早之前也是没有的,后来router更新了一次有了
为什么会报这个错误,为了防止重复渲染组件,抛出来的一个错误
那么如何解决?
 1. 在使用 $router.push() 的时候做处理
   

  $router.push()
      .then((result) => {}).catch((err) => {
       
     });


    可以使用catch捕获到这个错误,不打印即可
    一般不用第一种解决办法,为什么?
    因为不可能每次写 $router.push() 去catch
// 2. 重写push方法即可(在router.js中)

//重写push方法
const originPush = VueRouter.prototype.push; // 把官方的push方法暂存到originPush这个变量里面
VueRouter.prototype.push = function push (location) { // 参数是调用push方法传进来的参数
    return originPush.call(this, location).catch(() => {});
}
-------------------------------------------
//或者重写replace方法
const originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace (location) {
    return originReplace.call(this, location).catch(() => {})
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值