Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location

报错:Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/xxx". at createRouterError
这个错误是说着在promise里捕获了一个导航的重复定义,因为这里是使用编程式导航去进行路由跳转的,$router.push方法会返回一个promise对象。在这里重复的push了同一个路由地址,所以就报了这个错误。
有时也会报这个错Uncaught (in promise) Error: Navigation cancelled from "/xxx" to "/xxx" with a new navigation

例子如下:

<template>
  <div @click="toDetail(item.articleId)">
    <el-button @click="toDetail(item.articleId)">阅读</el-button>
  </div>
</template>

<script>
export default{
  methods:{
    toDetail(id) {
      this.$router.push({ name: 'detail', params: { articleId: id } })
    }
  }
}
</script>

因为el-button是在div里的,所按钮点击的时候会有两个click都调用了相同的push

错误解决

方法一:
把嵌套的子元素中的触发路由的事件去掉,这里把el-button中的click去掉就行了。

方法二:
因为这个错误是在push中抛出的,所以在其中捕获catch这个错误就行了,不过这似乎是个治标不治本的办法,所有在push中的错误都可以用此法捕获。
在路由中,添加如下代码进行配置:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 捕获push replace中的错误
// 当然在replace中的错误也是可以相同的进行捕获
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

参考:
https://www.cnblogs.com/flytree/p/14669009.html

posted on   铃之森  阅读(370)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示