vue中使用visibilitychange

1,785 阅读1分钟

背景描述

有一个对象数组其中保存了时间与值格式如下:let arr = [{t:时间,v:值}] 保存近两个小时的数据。数组长度一定,使用定时器间隔30秒计算一次数据,删除数组第一个元素,将最新的数据添加数组最后。

问题描述

当我的浏览器窗口最小化或者切换至别的网页时,那该页面的定时器暂停。过多时间再次切换回来时,定时器激活,这时我的时间数组中的数据将存在异常。

解决方案

使用visibilitychange监听窗口的是否可见,当可见是重新对时初始化

mounted() {
    //首次执行初始化
    this.init();
    this.timer = setInterval(() => {
        //定时执行
      this.getData();
    }, 3000);
    //使用visibilitychange监听窗口的是否可见
    document.addEventListener("visibilitychange", this.handleVisiable);
},
methods: {
    handleVisiable(e) {
        //窗口可见时处理
      if (e.target.visibilityState === "visible") {
        //重新对时初始化
        this.init();
      }
    },
    getData(){
    //我的业务操作数据
     arr.shift();
     arr.push(v);
    },
    //初始化
    init(){
      let d = new Date();
      d.setHours(d.getHours() - 1);
      this.startDate = d;
      arr = []
    }
},
//销毁
beforeDestroy() {
    clearInterval(this.timer);
    this.timer = "";
    document.removeEventListener("visibilitychange", this.handleVisiable);
},