问题

Vue路由当你重复传相同参数时,控制台就会报:NavigationDuplicated


原因:

最新的vue-router引入了promise


解决方法

通过给push方法传递相应的成功,失败的回调,可以捕获当前错误,可以解决问题

this.$router.push({
name: 'search',
query: {
k: this.keyword.toUpperCase(),
},
params: {
keyword: this.keyword,
},
​
},
() => { },  //函数传入成功
() => { }   //函数传入失败
);

但是这种方法治标不治本


重写Router原型对象上的push方法和replace方法

//配置路由的主文件
import Vue from 'vue'
import Router from 'vue-router'
​
//使用插件
Vue.use(Router);
//打印路由原型
// console.log(Router.prototype);
​
//备份Router原型对象的push方法
let originPush = Router.prototype.push;
// console.log(originPush);
​
//备份Router原型对象的replace方法
let originReplace = Router.prototype.replace;
​
//重写push和replace方法
//第一个参数:路由路径以及传递的参数
//第二个参数:成功的回调
//第三个参数:失败的回调
//this:当前的路由对象(当前组件实例对象)
//call和apply的区别:都是改变this指向,但是call和apply的区别是:call是把参数传递给函数,apply是把参数传递给函数的数组
Router.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        return originPush.call(this, location, resolve, reject);
    } else {
        return originPush.call(this, location, () => { }, () => { });
    }
}
Router.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        return originReplace.call(this, location, resolve, reject);
    } else {
        return originReplace.call(this, location, () => { }, () => { });
    }
}
​
​
//配置路由
export default new Router({
    //配置路由
    routes: [
        {
            path: '/home',
            component: Home,
            meta: { show: true }
        },
    ]
})

至此push和replace重复提交问题以全部解决