用原生的方法过于复杂, 且无法满足同一页面需要特定前进后头的场景
//改写replace 和 push 方法 ,去除警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch((err) => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch((err) => err)
}
最后采用的方法 //组件内单独路由守卫
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
if (to.fullPath === '/index' && from.fullPath === '/statistics') {
// this.$router.replace('/statistics') //可能内部修改了history,造成只会触发一次守卫
// window.location.reload() //可能内部修改了history,造成只会触发一次守卫
next(false)
} else {
next()
}
},