路由跳转有两种形式:声明式导航、编程式导航
声明式导航没有这类问题,因为vue-router底层已经处理好了
为什么编程式导航进行路由跳转式就有这种警告呢???
因为vue-router大于3.0版本的,引入了promise导致的
解决方案如下:
第一种:通过给push或replace方法传递相应的成功、失败的回调函数,可以捕获当前错误,代码如下:
this.$router.push(
{
name:"search",
params:{title:this.title},
query:{username:this.username}
},
// 添加成功或失败的回调函数
()=>{},
()=>{}
)
第二种:通过重写push和replace方法,在配置路由的文件(router=>index.js)里面重写push和replace方法,代码如下:
// 在重写push|replace方法时,先把VueRouter原型对象的push|replace保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
/**参数1:告诉原来的push | replace方法,你往那里跳转(传递哪些参数)、参数2:成功回调、 参数3:失败回调**/
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, () => { }, () => { })
}
}
注意:推荐使用第二种方案,第一种解决方案不能从根本上解决问题,如果在别的组件中使用push或replace方法进行跳转时,还是会有类似错误,所以不建议使用。