vue-router在3.1之后,将push和replace方法改为了Promise 报错原因:当第二次push/replace的路径都一致时(没有传入回调函数),便会报这个错误 此报错,不会影响正常的业务逻辑
报错示例图:
解决方案一:
从版本上解决,将vue-router的版本降到3.1以下(不推荐)
npm install vue-router@3.0 --save
解决方案二:
每次使用push或replace方法时,捕获push或replace方法的报错,或者传入回调函数,控制台就不会抛错了
此方式需要每次都捕获错误
this.$router.push(location).catch(e=>e);
解决方案三(推荐):
重写vue-router的push、replace方法
- 在router/index.js中编写(以push方法为例) ```javascript // 先将路由的push方法保存下来 const originPush = VueRouter.prototype.push
// 重写push方法 VueRouter.prototype.push = function(location,resolve,reject){ if (resolve||reject) return originPush.call(this,location,resolve,reject) // 使用call改变this指向,原指向window,现在指向router return originPush.call(this,location).catch(()=>{}) } ```