vue项目设置定时请求接口

vue yekong 432℃

vue数据可视化大屏项目中,客户的数据大屏是投放到电视上的,不用操作,所以客户想每隔5秒请求一次接口刷新数据。

配置文件增加定时间隔

因为数据大屏项目中有很多接口,所以我们需要将定时间隔抽离出来,下次如果修改定时请求间隔或者不要定时请求了我们只需要修改配置文件就可以了。

我们在src/config/config.js中来写我们的定时间隔

// 当为0的时候不执行定时 否则执行定时 单位毫秒 1000为1秒
export const TIMER_INTERVAL = 5000; 

请求接口调整

引入定时配置文件,组件加载后触发定时,当定时间隔为0的时候,则只请求一次接口不触发定时,当组件销毁后清除定时

import {TIMER_INTERVAL} from '@/config/config.js'
mounted() {
    this.startDataInterval();
  },
  beforeDestroy() {
    // 清除定时器,当组件销毁时
    if (this.dataInterval) {
      clearInterval(this.dataInterval);
    }
  },
  methods: {
    async getData() {
      const response = await getTemp({room_id: this.roomId, date_time: this.active});
      this.data = response.data;
    },
    startDataInterval() {
      this.getData();  // 首先立即执行一次
      if (TIMER_INTERVAL > 0) {
        this.dataInterval = setInterval(this.getData, TIMER_INTERVAL);
      }
    },
  },

项目应用

智慧医疗数据展示平台

喜欢 (0)