解決Vue-Router升級導致的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,因為應用程序?qū)嶋H上沒有生成任何錯誤。它只是一個導航($router.push),在beforeEnter鉤子中生成重定向(next('/ foo'))
Vue-router >= 3.1.0 版本在使用 push 和 replace 進行跳轉(zhuǎn)時控制臺會拋出異常,其主要原因是 vue-router 3.1.0 版本以后 router.push('/path') 返回了 promise ,而當路由跳轉(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升級導致的Uncaught (in promise)問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue利用vue-baidu-map實現(xiàn)獲取經(jīng)緯度和搜索地址
在開發(fā)項目的時候,發(fā)現(xiàn)需要獲取經(jīng)緯度,由于這個項目是用vue寫的,最后決定使用vue-baidu-map來快速獲取經(jīng)緯度,感興趣的可以了解一下2022-09-09