vue3虚拟列表

在这里插入图片描述

<template>
  <div class="box" @scroll="handleScroll">
    <div :style="{ height: `${itemHeight * itemCount}px` }">
      <div
        v-for="(item, index) in renderList"
        :key="index"
        class="item"
        :style="{ transform: `translateY(${offsetY}px)` }"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";

// 渲染item数量
const itemCount = 10_0000;

// 每个item的高度
const itemHeight = 32;

// 创建数据列表
const list = computed(() =>
  Array.from({ length: itemCount }).map((c, i) => `某某数据${i + 1}`)
);

// 要渲染的list
const renderList = ref([]);

let start = 0;
// 偏移量
let offsetY = 0;
// 可视区域渲染的数量
let volume = 0;

// 滚动事件
const handleScroll = (e) => {
  const scrollTop = e.target.scrollTop;
  let currentStart = Math.floor(scrollTop / itemHeight);
  if (start != currentStart) {
    offsetY = scrollTop - (scrollTop % itemHeight);
    start = currentStart;
    renderList.value = list.value.slice(start, start + volume);
  }
};

onMounted(() => {
  volume = Math.ceil(300 / itemHeight) + 5;
  renderList.value = list.value.slice(start, volume);
});
</script>

<style>
.box {
  height: 300px;
  width: 1000px;
  margin: 100px auto;
  border: 1px solid #888;
  max-height: 300px;
  overflow-y: auto;
}
.item {
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  transform: background-color 0.3s;
}
.item:hover {
  background-color: skyblue;
}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值