虚拟列表

 先更新代码,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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值