为什么会用到监听隐藏显示窗口的事件呢?
主要是因为页面中有计时器,窗口隐藏页面隐藏后,计时器暂停,这里使用了重新获取数据,重新启动倒计时的功能解决,所以需要监听事件。
methods: {
visibilityState() {
if (document.visibilityState === 'visible' || event.persisted) {
console.log('欢迎回来!')
// this.$router.go(0)
this.onLoad()
// do something
// 继续
}
// if (document.visibilityState === "hidden") {
// console.log("不要走!")
// do something else
// 暂停
// }
}
},
mounted() {
window.addEventListener('visibilitychange', this.visibilityState)
window.addEventListener('pageshow', this.visibilityState)
},
beforeDestroy() {
window.removeEventListener('visibilitychange', this.visibilityState)
window.removeEventListener('pageshow', this.visibilityState)
}
下面的函数封装,监听效果不理想,最终使用的是上面的方法
mounted() {
this.pageListener(this.handlePage, true)
},
beforeDestroy() {
this.pageListener(this.handlePage)
},
methods: {
handlePage(event) {
console.log(event, document.visibilityState)
if (document.visibilityState === 'visible' || event.persisted) {
console.log('欢迎回来!', event.persisted)
this.onLoad()
}
},
pageListener(callback, addListener) {
if (addListener) {
console.log('pageListener addListener')
window.addEventListener('pageshow', callback, false);
document.addEventListener('visibilityChange', callback, false);
} else {
console.log('pageListener remove')
// 移除页面监听
this.pageShowListener(callback, false);
this.pageVisibilityListener(callback, false);
}
},
pageShowListener(callback) {
window.removeEventListener('pageshow', callback)
},
pageVisibilityListener(callback) {
document.removeEventListener('visibilitychange', callback)
}
}
标签:Vue,visibilityState,log,--,callback,window,console,document,监听
From: https://www.cnblogs.com/lisaShare/p/16642375.html