实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<script>
export default {
data() {
return {
pollingST: null, // 定义一个计时器
isPolling: false, // 定义一个标志变量
}
},
mounted() {
this.polling()
document.addEventListener('visibilitychange', this.handleVisibilityChange)
},
methods: {
polling() {
if (this.isPolling) return // 如果已经在轮询,直接返回
this.isPolling = true // 设置标志变量为 true
// 定时器,每秒执行一次
this.pollingST = setInterval(() => {
// 获取当前时间,格式YYYY-MM-DD HH:mm:ss
let now = new Date().toLocaleString()
// 显示在控制台
console.log(now)
}, 1000)
},
handleVisibilityChange() {
if (document.visibilityState === 'hidden') {
clearInterval(this.pollingST)
this.isPolling = false // 设置标志变量为 false
} else if (document.visibilityState === 'visible') {
this.polling()
}
},
},
beforeDestroy() {
// 组件销毁时,清除定时器
clearInterval(this.pollingST)
document.removeEventListener('visibilitychange', this.handleVisibilityChange)
},
}
</script>

这段代码会监听 visibilitychange 事件,当页面不显示时,会自动停止轮循,再次进入该页面时会重新进行轮询,然后跳转到其他页面时也会销毁定时器,这样就避免了没必要的请求