<template>
<div class="virtual-list">
<ul>
<li v-for="item in visibleItems" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `Item ${i}` })),
startIndex: 0,
endIndex: 9,
itemHeight: 50,
containerHeight: 500
};
},
computed: {
visibleItems() {
return this.items.slice(this.startIndex, this.endIndex + 1);
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = window.scrollY;
const start = Math.floor(scrollTop / this.itemHeight);
const end = start + Math.ceil(this.containerHeight / this.itemHeight);
this.startIndex = start;
this.endIndex = end;
}
}
};
</script>
<style scoped>
.virtual-list {
height: 500px;
overflow-y: auto;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
height: 50px;
line-height: 50px;
border-bottom: 1px solid #ccc;
}
</style>
数据准备:
items
: 包含1000个元素的数组,模拟大数据量。startIndex
和 endIndex
: 分别表示当前可见区域的起始和结束索引。itemHeight
和 containerHeight
: 每个列表项的高度和容器的高度。计算属性:
visibleItems
: 根据 startIndex
和 endIndex
计算当前可见的列表项。生命周期钩子:
mounted
: 添加滚动事件监听器。beforeDestroy
: 移除滚动事件监听器,防止内存泄漏。方法:
handleScroll
: 监听滚动事件,根据滚动位置更新 startIndex
和 endIndex
,从而动态显示当前可见的列表项。样式:
.virtual-list
的高度和溢出属性,确保可以滚动。li
元素的高度和样式,使其一致且美观。上一篇:datav vue3
下一篇:arttemplate vue
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站