解决Vue报错: Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current locatio

文章介绍了在VueRouter3.0版本后,由于使用Promise处理路由跳转导致的`NavigationDuplicated`错误。提供了两种解决方法:重写push和replace方法,以防止重复导航并确保性能。

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

无废话篇,直接上解决办法

原因:这是因为你多次触发路由跳转事件,且跳转的url地址都是同一个。

解决方法:重写push / replace方法

在入口文件(main.js)中添加
import VueRouter from 'vue-router'

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
   return originalReplace.call(this, location).catch(err => err)
}

new Vue({
  render: h => h(App)....

上面的代码还有第二种写法,实现原理都一样

import VueRouter from 'vue-router'

let originPush =VueRouter.prototype.push;
let originReplace =VueRouter.prototype.replace;
VueRouter.prototype.push=function(location,resolve,reject){
  if(resolve&&reject){
    originPush.call(this,location,resolve,reject)    
  }else{
    originPush.call(this,location,()=>{},()=>{})
  }
}
VueRouter.prototype.replace=function(location,resolve,reject){
  if(resolve&&reject){
    originReplace.call(this,location,resolve,reject)
  }else{
    originReplace.call(this,location,()=>{},()=>{})
  }
}

new Vue({
  render: h => h(App)....
 第二种方式:在push方法后面加上两个参数resolve和reject
this.$router.push('/search/'+this.keyWord)

替换成

this.$router.push('/search/'+this.keyWord,()=>{},()=>{})

废话部分:(解释一下原理)

这个问题是在vue-router在3的版本之后就有的,原因是因为编程式路由在使用push或者replace方法进行路由跳转,底层是使用了ES6中的Promise,每次push或者replace之后就会返回一个promise对象,能够执行回调处理导航成功或者失败的情况。

为什么会报NavigationDuplicated错误?这其实是Vue Router 提供了一种机制来避免重复导航,从而提高应用程序的性能和稳定性。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焦油坑中挣扎的巨兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值