码迷,mamicode.com
首页 > 其他好文 > 详细

Vue使用定时器定时刷新页面

时间:2020-07-14 18:29:06      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:http   blog   数据   article   tps   退出   str   刷新数据   计时   

1. 需求说明

在前端开发中,往往会遇到页面需要实时刷新数据的情况,给用户最新的数据展示。

2. 逻辑分析

如果需要数据实时更新,我们自然是需要使用定时器,不断的调用接口数据,会相对的消耗内存。

3. 代码示例

data(){
    return {
        intervalId:null
    }
},
methods:{
   // 定时刷新数据函数
    dataRefreh() {
      // 计时器正在进行中,退出函数
      if (this.intervalId != null) {
        return;
      }
      // 计时器为空,操作
      this.intervalId = setInterval(() => {
        console.log("刷新" + new Date());
        this.initData(); //加载数据函数
      }, 5000);
    }, 
    // 停止定时器
    clear() {
      clearInterval(this.intervalId); //清除计时器
      this.intervalId = null; //设置为null
    },
},
created(){
    this.dataRefreh();
},
destroyed(){
    // 在页面销毁后,清除计时器
    this.clear();
}

4. 代码分析

  • 首先选择数据刷新的时机,在created中。
  • 声明计时器,与数据刷新函数。
  • 在页面销毁的时机(destroyed),关闭计时器等耗时操作。

本文转自:https://blog.csdn.net/qq_41115965/article/details/102722540

Vue使用定时器定时刷新页面

标签:http   blog   数据   article   tps   退出   str   刷新数据   计时   

原文地址:https://www.cnblogs.com/aurora-ql/p/13300202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!