<template>
<div class="virtual-list">
<div class="scrollView" @scroll="onScroll" ref="list">
<!-- 虚拟列表 -->
<div class="virtualScroller" :style="{ height: listHeight + 'px' }"></div>
<div class="list" :style="{ transform: `translateY(${startOffset}px)` }">
<div class="item" v-for="item in list" :key="item">
{{ item }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
listHeight: 0,
itemSize: 50,
containerHeight: 500,
visibleCount: 11,
data: [],
startOffset: 0,
};
},
mounted() {
const total = 100000;
const list = [];
for (let i = 0; i < total; i++) {
list.push(i);
}
this.listHeight = list.length * this.itemSize;
this.data = list;
this.list = list.slice(0, 11);
},
methods: {
onScroll() {
//当前滚动位置
let scrollTop = this.$refs.list.scrollTop;
// 列表开始索引
let startIndex = Math.floor(scrollTop / this.itemSize);
// 列表结束索引
let endIndex = Math.ceil((scrollTop + this.containerHeight) / this.itemSize);
this.list = this.data.slice(startIndex, endIndex);
// 列表移动距离
this.startOffset = scrollTop - (scrollTop % this.itemSize);
}
}
};
</script>
<style>
.scrollView {
width: 200px;
height: 500px;
background-color: rgb(250, 138, 138);
overflow-y: scroll;
position: relative;
}
.item {
height: 50px;
}
.list {
position: absolute;
top: 0;
left: 0;
}
</style>
vue简单虚拟列表
于 2024-02-26 18:08:41 首次发布