zoukankan      html  css  js  c++  java
  • Vue使用定时器定时刷新页面

    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

  • 相关阅读:
    Maximal Square
    Count Complete Tree Nodes
    Rectangle Area
    Implement Stack using Queues
    Basic Calculator
    Invert Binary Tree
    Summary Ranges
    Basic Calculator II
    Majority Element II
    Kth Smallest Element in a BST
  • 原文地址:https://www.cnblogs.com/aurora-ql/p/13300202.html
Copyright © 2011-2022 走看看