Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/xxx". at createRouterError 的說明和解決


錯誤說明

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)
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM