<template>
<div class="virtual-scroll-container" ref="container">
<div class="scrollable-content" :style="{ transform: `translateY(${offset}px)` }">
<div v-for="item in visibleItems" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: Array.from({ length: 1000 }, (_, i) => ({ id: i, content: `Item ${i + 1}` })),
containerHeight: 300,
itemHeight: 50,
visibleCount: 0,
startIndex: 0,
offset: 0
};
},
computed: {
visibleItems() {
return this.items.slice(this.startIndex, this.startIndex + this.visibleCount);
}
},
mounted() {
this.$refs.container.addEventListener('scroll', this.handleScroll);
this.updateVisibleItems();
},
methods: {
updateVisibleItems() {
this.visibleCount = Math.ceil(this.$refs.container.clientHeight / this.itemHeight) + 2;
this.startIndex = Math.floor(this.$refs.container.scrollTop / this.itemHeight);
this.offset = this.startIndex * this.itemHeight - this.$refs.container.scrollTop;
},
handleScroll() {
this.updateVisibleItems();
}
},
beforeDestroy() {
this.$refs.container.removeEventListener('scroll', this.handleScroll);
}
};
</script>
<style scoped>
.virtual-scroll-container {
height: 300px;
overflow-y: auto;
}
.scrollable-content {
transition: transform 0.1s ease-out;
}
.item {
height: 50px;
border-bottom: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
}
</style>
模板部分 (<template>):
div 容器来包裹所有可滚动的内容。scrollable-content 是实际包含内容的容器,通过 CSS 的 transform 属性实现平滑滚动。v-for 指令用于渲染当前可见的项。脚本部分 (<script>):
data 中定义了虚拟滚动所需的数据:items: 模拟的大量数据。containerHeight: 容器的高度。itemHeight: 每个项的高度。visibleCount: 当前可见的项数。startIndex: 当前显示项的起始索引。offset: 用于计算偏移量。computed 计算属性 visibleItems 返回当前可见的项。mounted 生命周期钩子中添加滚动事件监听,并初始化可见项。methods 中定义了更新可见项和处理滚动事件的方法。beforeDestroy 生命周期钩子中移除滚动事件监听。样式部分 (<style scoped>):
transition 实现平滑滚动效果。上一篇:vue 时间戳
下一篇:vue3安装scss
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站