前端数据列表使用轮询获取实时数据

537 阅读1分钟

背景:

像是前台的列表数据,如果是上报信息类数据或者是一些后台系统控制的数据等,都不一定是最新的,因为有可能你在获取列表数据后,后台进行了操作,数据可能就会发送一些改变,所以这时候就要用到轮询技术,给定一个时间间隔让列表数据持续更新。

代码:

以Vue2为例(用了keep alive)

module.exports = Vue.extend({
    activated() {
        this.searchListData().finally(() => {
            this.pollingData();
        });
    },
    methods: {
        // 查询列表数据
        searchListData() {
          return this.getList();
        },
        getList() {
            return Promise(resolve,reject) => {
                const params = {
                  ...
                };
                // 网络请求成功获取数据
                networkRequest(params).then((res) => {
                    console('res------', res)
                }).catch((err) => {
                    this.$message({
                        message: err,
                    });
                }).finally(() => {
                    resolve()
                })
             }
        },
        // 轮询数据
        pollingData() {
          const refreshData = () => {
              const params = {
                  ...
              };
              networkRequest(params).then((res) => {
                  const { records } = res;
              }).finally(() => {
                  this.pollingData()
              })
          }
          window.rainCollectionTimer = window.setTimeout(() => {
              window.clearTimeout(window.rainCollectionTimer)
              refreshData()
          }, 60 * 1000)
        },
    }
})