监听页面可见性

2021-11-29  本文已影响0人  Mr老朝

代码示例:

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),
            };
        },
        ....
}
上一篇下一篇

猜你喜欢

热点阅读