当后台返回十万条数据时实现虚拟滚动

55 阅读1分钟
  <div>
    <div
      class="scrollbar"
      ref="scrollbar"
      :style="{ height: '600px', overflow: 'auto' }"
      @scroll="scrollContent"
    >
      <!-- <a-list itemLayout="horizontal" :dataSource="listData"> -->
      <div
        :style="{
          height: `${itemheight * listData.length}px`,
          position: 'relative',
        }"
      >
        <div
          :style="{
            position: 'absolute',
            top: `${contentTop}px`,
            width: '100%',
          }"
        >
          <div
            class="list-item"
            slot="renderItem"
            v-for="(item, index) in showlist"
            :key="index"
          >
          {{item}}-- item
          </div>
        </div>
      </div>
      <!-- </a-list> -->
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      contentTop: 0,
      scrollTop: 0, //卷起的高度
      showlist: [], //可视区的数据列表
      listData:[],
      contentheight: 767, //可视区总高300
      itemheight: 30, //行高
      showNum: 0, //每页展示个数
      startindex: 0, //可视区第一条数据的索引
      enindex: 0, //最后一条数据的索引
    }
  },
  created () {
    for(let i = 0; i < 1000; i++) {
      // this.showlist.push(i)
      this.listData.push(i)
    }
    
  },
  mounted () {
    this.scrollContent()
  },
  methods: {
    scrollContent () {
      this.scrollTop = this.$refs.scrollbar.scrollTop

      this.getshowlist()
    },
    getshowlist () {

      this.showNum = Math.ceil(this.contentheight / this.itemheight) //每页展示条数
      this.startindex = Math.floor(this.scrollTop / this.itemheight) //开始数据的索引
      this.enindex = this.startindex + this.showNum //结束的索引
      this.showlist = this.listData.slice(this.startindex, this.enindex)
      const offsetY = this.scrollTop - (this.scrollTop % this.itemheight)
      this.contentTop = offsetY
    },
  }
}
</script>

<style>
.scrollbar {
  height: 600px;
}
.list-item {
  height: 30px;
  line-height: 30px;
}
</style>