vue中一次性加载万条数据优化方案

<template>
  <div>
    <ul>
      列表
      <li v-for="(item, key) in list" :key="key">{{ item }}------{{ key }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //处理后的数据
      list: [],
      //请求的数据
      data: [],
      //数据总条数
      total: 10000,
      //每次加载数据量
      once: 50,
      //已渲染的数据个数
      countOfRender: 0,
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    // 模拟数据
    async loadData() {
      try {
        let res = await new Promise((resolve) => {
          let data = [];
          for (let i = 0; i < this.total; i++) {
            data.push(i);
          }
          resolve({ total: this.total, data });
        });
        // 模拟赋值
        this.data = res.data;
        this.total = res.total;
        this.renderItems();
      } catch (error) {
        console.error("Error......", error);
      }
    },
    // 优化加载
    renderItems() {
      setTimeout(() => {
        const remainingData = this.data.slice(
          this.countOfRender,
          this.countOfRender + this.once
        );
        this.list = this.list.concat(remainingData);
        this.countOfRender += this.once;
        if (this.countOfRender < this.total) {
          this.renderItems();
        }
      }, 700);
    },
  },
};
</script>

你可能感兴趣的:(vue.js,javascript,ecmascript)