我遇到这个问题的场景是,我在header组件里一直点击一个播放按钮,这个按钮会跳转到webSocket页面,但控制台会报很多个这样的警告:Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/webSocket/2"
百度翻译是:未捕获(承诺中)导航重复:避免了到当前位置的冗余导航:“/webSocket?ken=222222222222”。
通过字面意思是说,路由跳转重复了,
路由跳转有两种方式:
声明式导航:router-link vue官方已经为路由跳转重复这个问题做了处理。
编程式导航:组件实例的$router.push ,官方没有做,需要重写push函数
重写push和replace方法
在router.js里
import Vue from 'vue'
import Router from 'vue-router'
//console.log(Router.prototype);
// 把Router 原型链push函数保存一份
let originPush = Router.prototype.push
// 把Router 原型链replace函数保存一份
let originReplace = Router.prototype.replace
// 重写push函数
Router.prototype.push = function(location,resolve,reject){
if (resolve && reject){
// call 和 apply
// 相同点:都能执行函数一次,都能篡改函数的上下文一次
// 不同点,call 多个参数用,隔开,apply 多个参数为数组
originPush.call(this, location, resolve, reject)
}else{
originPush.call(this, location, () => { }, () => { })
}
}
// 重写replace函数
Router.prototype.replace = function (location, resolve, reject) {
if (resolve && reject) {
// call 和 apply
// 相同点:都能执行函数一次,都能篡改函数的上下文一次
// 不同点,call 多个参数用,隔开,apply 多个参数为数组
originReplace.call(this, location, resolve, reject)
} else {
originReplace.call(this, location, () => { }, () => { })
}
}
export default new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap
})
使用:
this.$router.push({
name: 'webSocket',
query: { ken: '2222222222222' },
},()=>{},(error)=>{console.log(error)})
或
this.$router.push({
name: 'webSocket',
query: { ken: '2222222222222' }
)
play () {
this.$router.push({
name: 'webSocket',
query: { ken: '2' },
})
}