实现代码
| 12
 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
 
 this.pollingST = setInterval(() => {
 
 let now = new Date().toLocaleString()
 
 console.log(now)
 }, 1000)
 },
 handleVisibilityChange() {
 if (document.visibilityState === 'hidden') {
 clearInterval(this.pollingST)
 this.isPolling = false
 } else if (document.visibilityState === 'visible') {
 this.polling()
 }
 },
 },
 beforeDestroy() {
 
 clearInterval(this.pollingST)
 document.removeEventListener('visibilitychange', this.handleVisibilityChange)
 },
 }
 </script>
 
 | 
这段代码会监听 visibilitychange 事件,当页面不显示时,会自动停止轮循,再次进入该页面时会重新进行轮询,然后跳转到其他页面时也会销毁定时器,这样就避免了没必要的请求