路由多次执行相同push|replace报错问题
push是一个promise,promise需要传递成功和失败两个参数,我们的push中没有传递。
原因:vue-router3.1.0之后, 引入了push()的promise的语法,如果没有通过参数指定成功或者失败回调函数,就返回一个promise来指定成功/失败的回调。且内部会判断如果要跳转的路径和参数都没有变化,会抛出一个失败的promise
解决方法一:传递成功回调和失败回调
每次跳转都手动传递两个“()=>{}”
this.$router.push({ name:'search', params:{ keyword:this.keyword||undefined }, query:{ id:this.id } },()=>{},()=>{})
解决方法二:重写push和replace方法
一次解决问题,不用每次都传递两个“()=>{}”
//路由配置文件 import Vue from 'vue'; import VueRouter from 'vue-router'; //使用VueRouter插件 Vue.use(VueRouter); //先保存一份VueRouter let originPush = VueRouter.prototype.push; let originReplace = VueRouter.prototype.replace; //重写push|replace //第一个参数:往哪里跳(传递哪些参数) VueRouter.prototype.push = function(location,resolve,reject) { if(resolve && reject) { originPush.call(this,location,resolve,reject); } else { originPush.call(this,location,()=>{},()=>{}); } } VueRouter.prototype.replace = function(location,resolve,reject) { if(resolve && reject) { originReplace.call(this,location,resolve,reject); } else { originReplace.call(this,location,()=>{},()=>{}); } }