本來不想將博客作爲一個記錄踩坑筆記的地方,就想沒事寫個心情文吖,沒想到,又踩坑了。(估計以後還會踩坑很多,因爲到了新公司用的和之前都不一樣了。。。。)
一、問題描述
使用vue-router跳轉相同路由的時,比如在 /defend 路由下,使用 this.$router.push(’/defend’)再次跳轉當前路由,控制檯會報以下錯誤。
簡單的意思就是:導航重複了(NavigatingDuplicated
),message中也說了,不允許導航到當前位置(Navigating to current location ("/defend") is not allowed),話說我之前路由沒有這個問題啊?
Uncaught (in promise)
NavigationDuplicated {_name: “NavigationDuplicated”, name: “NavigationDuplicated”, message: “Navigating to current location (”/defend") is not allowed", stack: “Error↵ at new NavigationDuplicated (webpack-int…node_modules/vue/dist/vue.runtime.esm.js:2178:14)”}
二、解決問題
- 出現問題的原因
老項目沒有這個問題,新項目突然路由跳轉出現了報錯,首先看了一下新項目package.json中的vue-router的版本號 3.1.6,掐指一算,可能是路由更新導致的。 - 解決:知道問題的原因了,那麼就想辦法唄
- 將vue-router回退到老版本
- 重寫vue-router的push方法
- 重寫
我是在main.ts文件中重寫的
import Vue from 'vue'
import App from './App'
import Router from 'vue-router';
// 解決 vue-router 3.1.0+路由,重新進入相同路由時報錯的問題 Uncaught(in Promise)
const VueRouterPush = Router.prototype.push;
Router.prototype.push = function push(toLocation: 'string') {
return (VueRouterPush.call(this, toLocation) as any).catch((err: any) => err)
}
最後,解決了我目前路由跳轉當前頁面報錯的問題啦,如果以後遇見相關的問題,我會補充進去搭。