錯誤說明
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)
}