重写VueRouter的push/replace方法

重写VueRouter的push/replace方法


省流:复制代码粘贴到router文件中

编程式导航路由跳转到当前路由(参数不变), 多次执行会抛出vue-router.esm.js:1710 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/search?k=123”.的警告错误
错误实例
这种异常,对于程序运行没有任何影响。
由于vue-router最新版本3.5.2,引入了promise,push、replace方法会返回一个Promise。当传递参数多次且重复,或是没有写成功或失败的回调。会抛出异常,因此出现上面现象

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

import Vue from "vue"
import VueRouter from 'vue-router'
import Home from '../page/Home/index.vue'
import Login from '../page/Login/index.vue'
import Register from '../page/Register/index.vue'
import Search from '../page/Search/index.vue'

// 重写push|replace方法
//先把VueRouter的push和replace方法保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (location, resolve, reject) {
    // 此函数上下文(this指向)为VueRouter的一个实例
    if (resolve && reject) {    //如果我们自己指定了成功/失败的回调,则自己传入
        originPush.call(this, location, resolve, reject)
        //若此时直接使用originPush(),相当于调用了函数originPush(),则函数内的this指向window(内部代码将无法执行)。故应用call或apply方法修改this指向
    } else {    //如果我们没有指定成功/失败的回调,则自动帮我们生成,防止报错
        originPush.call(this, location, () => { }, () => { })
    }
}
// replace方法同理
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值