在Vue页面中实现手机锁屏后倒计时停止的功能,可以通过监听visibilitychange
事件来判断页面是否在可见状态。如果页面不可见(即锁屏状态),则清除倒计时;如果页面可见,则重新开始倒计时。
以下是一个简单的示例代码:
<template>
<div>
<p>倒计时: {{ countdown }}</p>
</div>
</template>
<script>
export default {
data() {
return {
countdown: 60, // 假设倒计时60秒
timer: null,
isPageVisible: true, // 页面是否可见的标志
};
},
created() {
this.startCountdown();
document.addEventListener('visibilitychange', this.handleVisibilityChange);
},
beforeDestroy() {
this.clearCountdown();
document.removeEventListener('visibilitychange', this.handleVisibilityChange);
},
methods: {
startCountdown() {
if (this.timer) return;
this.timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--;
} else {
this.clearCountdown();
}
}, 1000);
},
clearCountdown() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
handleVisibilityChange() {
if (document.visibilityState === 'visible' && this.isPageVisible === false) {
this.startCountdown();
} else if (document.visibilityState === 'hidden') {
this.clearCountdown();
}
this.isPageVisible = document.visibilityState === 'visible';
},
},
};
</script>
在这个示例中,当组件被创建时,倒计时开始,同时监听visibilitychange
事件。当页面变为不可见时(锁屏),清除倒计时;当页面再次变为可见时,倒计时重新开始。组件销毁前,清除计时器和事件监听器,以防止内存泄露。