vue 解决多次跳转到当前路由报错问题“NavigationDuplicated: Avoided redundant navigation to current location: “/home“.

参考链接:
https://www.jb51.net/article/280106.htm
https://blog.csdn.net/misschengispink/article/details/122058267
https://blog.csdn.net/weixin_43263566/article/details/127113293

解决方法:
在vue的路由route文件夹下的index.js,写以下代码

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 解决跳转到当前路由报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

以下内容来自于尚硅谷视频中
问题:编程式路由跳转到当前路由(参数不变),多次执行会抛出NavigationDuplicated的警告错误?
路由跳转有良种方式:声明式导航、编程式导航。
声明式导航没有这类问题,因为vue-router底层已经处理好了。

问题:为什么编程式导航进行路由跳转时候,就会有这种警告错误呢?
最新的vue-router引入promise。
通过给push方法传递相应的成功、失败的回调函数,可以捕获到当前错误,可以解决。
通过底部的代码,可以实现解决错误:this.$router.push({name: ‘search’,}, ()=>{}, () => {})。

// 在router文件中,写如下代码,即可解决
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 先把VueRouter原型对象的push方法,先保存一份
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

// 重写push|replace
// 第一个参数:告诉原来push方法,你要往哪里跳转(也就是要传递哪些参数)
// 第二个参数:成功回调
// 第三个参数:失败回调
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originalPush.call(this, location, resolve, reject);
  } else {
    originalPush.call(this, location, () => { }, () => { });
  }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originalReplace.call(this, location, resolve, reject);
  } else {
    originalReplace.call(this, location, () => { }, () => { });
  }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值