问题描述
形成原因
在升级了Vue-router版本到3.1.0及以上之后,新增了一些功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常
解决方法
- 方法一:vue-router版本降级
npm uninstall vue-router
npm install vue-router@3.0.7 -S
- 方法二:在调用方法的时候用catch捕获异常
this.$router.replace('/').catch(err => {
console.log('all good')
})
- 方法三:对Router原型链上的push、replace方法进行重写,这样就不用每次调用方法都要加上catch。
import Router from 'vue-router'
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)
}