错误 “Avoided redundant navigation to current location...” 的解决方案

当 vue 项目中使用 vue-router 的 编程式导航 写法进行路由切换时:

// Search/index.vue
<button @click="goSearch" v-model="keyword">搜索</button>  //按钮绑定事件,切换路由

methods: {
    goSearch() {
      this.$router.push({     //编程式导航
        name: 'search',
        params: {
          keyword: this.keyword,
        },
        query: {
          k: this.keyword.toUpperCase()
        }
      })
    }
  }

如果用户在页面 多次点击按钮 时,浏览器的控制台报如下错误:

错误原因: vue-router 实例上的 push 方法返回的是 promise 对象,所以传入的参数期望有一个成功和失败的回调,如果省略不写则会报错。

解决方案一:每次使用 push 方法时带上两个回调函数:

this.$router.push(`/search/${this.keyword}}`, ()=>{}, ()=>{})  
//第二、第三个参数分别为成功和失败的回调函数
      

解决方案二:重写 Vue-router 原型对象上的 push 函数:

let originPush =  VueRouter.prototype.push;  //备份原push方法

VueRouter.prototype.push = function (location, resolve, reject){
    if (resolve && reject) {    //如果传了回调函数,直接使用
        originPush.call(this, location, resolve, reject);
    }else {                     //如果没有传回调函数,手动添加
        originPush.call(this, location, ()=>{}, ()=>{}); 
    }
}

猜你喜欢

转载自blog.csdn.net/FunSober/article/details/127624178