区分普通页面/keep-alive缓存页面
1、普通页面
mounted: {
this.setAddListener()
},
destroyed() {
window.removeEventListener('popstate', this.setBack, false)
},
methods: {
//监听浏览器返回操作
setAddListener() {
const hasRefresh = this.$store.state.biz.hasRefresh;
if(window.history && window.history.pushState) {
!hasRefresh && history.pushState(null, null, document.URL); // 页面刷新不添加空地址
window.addEventListener('popstate', this.setBack, false)
}
},
setBack() {
if(this.back.hasBack) { // 允许返回
this.$router.back()
} else { // 禁止返回
history.pushState(null, null, document.URL);
this.back.visible = true
this.back.hasBack = false
return false
}
},
}
2、keep-alive页面
// 1、进入该页面时,会执行activated()函数
activated() {
this.setAddListener()
},
// 2、监听事件返回路径
methods:{
setAddListener() {
const hasRefresh = this.$store.state.biz.hasRefresh;
if(window.history && window.history.pushState) {
!hasRefresh && history.pushState(null, null, document.URL);
// history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.setBack, false)
}
},
setBack() {
if(this.back.hasBack) { // 允许返回
this.$router.back()
} else { // 禁止返回
history.pushState(null, null, document.URL);
this.back.visible = true
this.back.hasBack = false
return false
}
},
注意:离开该页面时,销毁事件解决方法有2种 :
// 3、直接调用deactivated
deactivated() {
window.removeEventListener('popstate', this.setBack, false);
},
// 3、配合导航守卫,手动调用生命周期销毁函数
beforeRouteLeave (to, from, next) {
window.removeEventListener('popstate', this.setBack, false);
next();
},