vue使用setTimeout实现实时刷新,避免定时器死循环

1、定义变量

timerval: null,
isLeave: false

2、在页面标签中添加 ref,获取页面dom元素,或者可以添加在需要定时刷新的dom元素上

 <div ref="timeouts"></div>

3、定义自动刷新方法

    // 刷新,获取列表
    refresh() {
      this.getAIBoxPageList();
    },
    // 设置刷新内容
    setFresh() {
      if (this.isLeave) return false;
      let self = this;
      let spacingTime = 10 * 1000;
      // var timerval;
      if (self.$refs.timeouts) {
        if (self.$refs.timeouts) {
          clearTimeout(self.timerval);
          self.timerval = null;
          self.isTimeout = true;
          let that = self;
          self.timerval = setTimeout(function timeout() {
            that.refresh();
            self.timerval = setTimeout(timeout, spacingTime);
          }, spacingTime);
        } else {
          self.isTimeout = false;
        }
        self.$once("hook:beforeDestroy", () => {
          clearTimeout(self.timerval);
        });
      } else {
        clearTimeout(self.timerval);
        self.timerval = null;
      }
      this.$once("hook:beforeDestroy", () => {
        clearTimeout(self.timerval);
        self.timerval = null;
      });
    },

4、在页面加载时,mounted生命周期中调用,监听浏览器tab标签切换事件

mounted() {
    // 搜索,筛选,获取ai盒子分页列表
    this.getAIBoxPageList();
    // 刷新
    this.setFresh();
    let self = this;
    document.addEventListener("visibilitychange", () => {
      //浏览器tab标签切换事件

      if (document.visibilityState == "hidden") {
        //状态判断 没在当前页面呆着
        console.log("离开了");
        self.isLeave = true;
        if (self.timerval) window.clearTimeout(self.timerval);
        self.timerval = null;
      } else {
        //回来了
        self.$once("hook:beforeDestroy", () => {
          self.isLeave = true;
          clearTimeout(self.timerval);
          self.timerval = null;
        });
        console.log("回来了");
        self.isLeave = false;
        self.setFresh();
      }
    });
}

5、页面销毁前,清除延时器,定义beforeDestroy生命周期

  beforeDestroy() {
    this.isLeave = true;
    clearTimeout(this.timerval);
    this.timerval = null;
  }

6、由于我开发的页面是有tab栏切换的,所以切换时需要清除或者重新添加定时刷新

    // 切换选项卡
    toggleTab(index) {
      this.active = index;
      if (this.active === 0) {
        this.PageInfo.PageIndex = 1;
        // 搜索,筛选,获取ai盒子分页列表
        this.getAIBoxPageList();
        this.isLeave = false;
        this.setFresh()
      } else if (this.active === 1) {
        this.PageInfo1.PageIndex = 1;
        // 获取教室列表(校区-教学楼-教室)
        this.getQueryRoomModelList();
        this.isLeave = true;
        clearTimeout(this.timerval);
        this.timerval = null;
      }
    },

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值