虚拟列表

 先更新代码,js注释很详细,后续更新详细的虚拟列表说明

<template>
  <div class="list-view" @scroll="handleScroll">
    <!-- 撑起这个列表,让列表的滚动条出现 -->
    <div
      class="list-view-phantom"
      :style="{
        height: contentHeight,
      }"
    ></div>
    <!-- 内容 -->
    <div ref="content" class="list-view-content">
      <!-- item 节点 -->
      <div
        class="list-view-item"
        :style="{
          height: itemHeight + 'px',
        }"
        v-for="(item, index) in visibleData"
        :key="index"
      >
        {
   
   { item }}
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //全部数据
      data: [...'自己写吧这里不占空间了'],
      // 可视区数据
      visibleData: [],
      //单个数据的高度
      itemHeight: 20,
    };
  },
  computed: {
    //内容高度
    contentHeight() {
      return this.data.length * this.itemHeight + "px";
    },
  },
  mounted() {
    this.updateVisibleData();
  },
  methods: {
    updateVisibleData(scrollTop) {
      scrollTop = scrollTop || 0;
      // 可视区的个数 = 当前可视区域的高度 / 每个数据的高度
      const visibleCount = Math.ceil(this.$el.clientHeight / this.itemHeight);
      // 取得可见区域的起始数据索引 = 被卷入的高度 / 每个数据的高度
      const start = Math.floor(scrollTop / this.itemHeight);
      // 取得可见区域的结束数据索引 = 取得可见区域的起始数据索引 + 可视区的个数
      const end = start + visibleCount;
      // 对原数据进行截取出可视区应该渲染的那部分数据,让 Vue.js 更新
      this.visibleData = this.data.slice(start, end);
      //把内容盒子进行位移  起始数据的索引 * 每个的高度
      this.$refs.content.style.webkitTransform = `translate3d(0, ${
        start * this.itemHeight
      }px, 0)`; // 把可见区域的 top 设置为起始元素在整个列表中的位置(使用 transform 是为了更好的性能)
    },
    handleScroll() {
      const scrollTop = this.$el.scrollTop;
      this.updateVisibleData(scrollTop);
    },
  },
};
</script>
<style>
.list-view {
  height: 400px;
  overflow: auto;
  position: relative;
  border: 1px solid #aaa;
}

.list-view-phantom {
// z-index 要和 定位 一起使用
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  z-index: -1;
}
</style>

猜你喜欢

转载自blog.csdn.net/m0_56274171/article/details/124178043
今日推荐