解決Vue-Router升級導(dǎo)致的Uncaught (in promise)問題
在升級了Vue-Router版本到到3.1.0及以上之后,頁面在跳轉(zhuǎn)路由控制臺會報Uncaught (in promise)的問題

這是什么原因呢?
看vue-router的版本更新日志
V3.1.0版本里面新增功能:push和replace方法會返回一個promise, 你可能在控制臺看到未捕獲的異常

解決方法一:在調(diào)用方法的時候用catch捕獲異常
this.$router.replace({ name: 'foo' }).catch(err => {
console.log('all good')
})
方法二: 對Router原型鏈上的push、replace方法進行重寫,這樣就不用每次調(diào)用方法都要加上catch。這個方法是vue-router的issues里面的一位大佬解決的
import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.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)
}
補充知識:vue-router使用$router.push(),頁面掛起進入debug模式,提示Uncaught (in promise) undefined
問題
vue-router使用$router.push()跳轉(zhuǎn)頁面時,頁面掛起進入debug模式,提示“Uncaught (in promise) undefined”,斷點進入
function (err) {
if (onAbort) {
onAbort(err);
}
……
}
此方法

分析()
Uncaught (in promise) undefined,未捕獲的promise,因為應(yīng)用程序?qū)嶋H上沒有生成任何錯誤。它只是一個導(dǎo)航($router.push),在beforeEnter鉤子中生成重定向(next('/ foo'))
Vue-router >= 3.1.0 版本在使用 push 和 replace 進行跳轉(zhuǎn)時控制臺會拋出異常,其主要原因是 vue-router 3.1.0 版本以后 router.push('/path') 返回了 promise ,而當(dāng)路由跳轉(zhuǎn)異常時便會拋出錯誤,此前版本沒有報錯是因為 vue-router 根本沒有返回錯誤信息,所以之前我們一直無法捕獲異常,而并非異常不存在。所以我們要做的就是在路由跑出異常時加上可以接收的回調(diào)就好了。
解決
1.使用route-link to bar代替$push
<router-link to="/settlement_manage/account">
<el-button :disabled="loading" size="mini" type="warning">
查看詳情
</el-button>
</router-link>
2.對所有調(diào)用進行push更新:
this.$router.push({
path: '/settlement_manage/account',
}, () => {});
3.使用時進行錯誤攔截
router.push('/path').catch(err => {})
4.顯式指定onComplete和onAbort回調(diào)函數(shù)
this.$router.push({
path: `/settlement_manage/account`
},
onComplete => {
console.log('完成')
},
onAbort => {
console.log('哦打斷了')
})
5.引入router之前重寫push方法,在router.js里加
const originalPush = VueRouter.prototype.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)
}

ok!以上所有方法親測有效~
以上這篇解決Vue-Router升級導(dǎo)致的Uncaught (in promise)問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue報錯"vue-cli-service‘不是內(nèi)部或外部命令,也不是...”的解決辦法
這篇文章主要介紹了vue報錯"vue-cli-service‘不是內(nèi)部或外部命令,也不是...”的解決辦法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
vue+axios?methods方法return取不到值問題及解決
這篇文章主要介紹了vue+axios?methods方法return取不到值問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
從vue基礎(chǔ)開始創(chuàng)建一個簡單的增刪改查的實例代碼(推薦)
這篇文章主要介紹了從vue基礎(chǔ)開始創(chuàng)建一個簡單的增刪改查的實例代碼,需要的朋友參考下2018-02-02
vue通過tailwindcss實現(xiàn)class動態(tài)綁定
這篇文章主要介紹了vue通過tailwindcss實現(xiàn)class動態(tài)綁定,文中給大家介紹了一些常用類名語法記錄,對vue動態(tài)綁定class相關(guān)知識感興趣的朋友一起看看吧2023-07-07

