vue-router报错Uncaught (in promise)及解决方法
# vue-router报错Uncaught (in promise)及解决方法
# 报错原因
在升级了Vue-Router版本到到3.1.0及以上之后,页面在跳转路由控制台会报Uncaught (in promise)的问题。
这是什么原因呢?
看vue-router的版本更新日志
V3.1.0版本里面新增功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常。
# 解决方法
方法一:在调用方法的时候用catch捕获异常
this.$router.replace('/home').catch(err => {
console.log(err)
})
1
2
3
2
3
方法二:对Router原型链上的push、replace方法进行重写,这样就不用每次调用方法都要加上catch
在router.js加入以下内容:
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)
}
1
2
3
4
5
6
7
2
3
4
5
6
7