Multiple data webSocket push too fast leads to optimization of front-end rendering freeze problem

The author's code is not very good, sorry! The main idea is to temporarily store the data received by websocket in an array, and modify the unified rendering together when a certain amount is reached. The size of the array can be adjusted appropriately according to the speed of project data push data, and then add another one that may not be available for a period of time. If the array reaches the standard rendering quantity, use the timer to render directly to prevent the data from changing

data() {
  return {
    tempDataWsList: [], // 存放临时ws数据数组
    list: [], // 页面上的列表
    listCopy: [], // 深拷贝的初始化列表数据,用于统一渲染
  }
}
methods: {
  ...
  // websocket接收数据的方法
  onMessage(data) {
    if (data.data) {
      // 将Json字符串转译
      const dataWs = JSON.parse(data.data);
      // 将转译后的数据推入临时ws数据数组中
      this.tempDataWsList.push(dataWs);
      // 有ws数据就关闭定时器
      clearTimeout(this.wsTimeout);
      // 做缓存渲染,将ws接收到的数据放到数组,满10个就统一渲染
      if (this.tempDataWsList.length == 10) {
        this.handleList();
      } else {
        // 如果最后一个接收后1秒钟内不能满足10个,则直接渲染
        this.wsTimeout = setTimeout(() => {
          this.handleList();
        }, 1000);
      }
    }
  },

  // 操作数据渲染
  handleList() {
    // 循环临时ws数据数组
    this.tempDataWsList.forEach(temp => {
      // 循环深拷贝的初始化列表数据
      this.listCopy.forEach(item => {
        // 循环判断列表对应ws数据id,修改深拷贝列表上的值
        item.pointDetails.forEach(item1 => {
          if (item1.id == temp.detailsId) {
            item1.value = temp.realVal;
          }
        });
      });
    });
    // 清空临时ws数据数组
    this.tempDataWsList = [];
    // 将修改的列表数据赋值给页面渲染
    this.list = this.listCopy;
  }
}

Guess you like

Origin blog.csdn.net/weixin_42627850/article/details/128964300