在升级了Vue-Router版本到到3.1.0及以上之后,页面在跳转路由时控制台会报Uncaught (in promise)的问题
这是什么原因导致的呢?我们看一下Vue-Router的版本日志就知道了
原因:V3.1.0版本里面新增功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常;
虽然不影响运行,但是看起来不太美观~
解决办法一:在调用方法的时候用catch捕获异常
this.$router.replace({ name: 'foo' }).catch(err => {
console.log('all good')
})
解决方法二:对Router原型链上的push、replace方法进行重写。这样就避免每次调用时还要加上捕获异常方法
此方法在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)
}