监听页面可见性
2021-11-29 本文已影响0人
Mr老朝
- 1、visibilitychange监听页面可见切换
- 2、document.visibilityState判断页面是可见、还是不可见
代码示例:
export default {
....
mounted: function () {
this.visibleChangeObject = this.visibleChange();
this.visibleChangeObject.add();
},
destroyed() {
this.visibleChangeObject.remove();
},
methods: {
pageVisible() {
console.log('visible');
},
pageHidden() {
console.log('hidden');
},
visibleChange() {
const handleVisibilityChange = () => {
if (document.visibilityState == 'hidden') {
this.pageHidden();
}
if (document.visibilityState == 'visible') {
this.pageVisible();
}
};
return {
add: () => document.addEventListener('visibilitychange', handleVisibilityChange, false),
remove: () => document.removeEventListener('visibilitychange', handleVisibilityChange, false),
};
},
....
}