vue实现滚动列表
Vue 实现滚动列表的方法
使用 CSS 实现基础滚动
通过 CSS 的 overflow 属性可以快速实现滚动效果。将列表容器的高度固定,并设置 overflow-y: auto。
<template>
<div class="scroll-container">
<div v-for="item in items" :key="item.id" class="list-item">
{{ item.text }}
</div>
</div>
</template>
<style>
.scroll-container {
height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
}
.list-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
使用第三方库实现高性能滚动
对于大数据量的列表,推荐使用 vue-virtual-scroller 或 better-scroll 等库优化性能。
安装 vue-virtual-scroller:
npm install vue-virtual-scroller
示例代码:
<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="item">
{{ item.text }}
</div>
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
export default {
components: { RecycleScroller },
data() {
return {
items: Array(1000).fill().map((_, i) => ({ id: i, text: `Item ${i}` }))
}
}
}
</script>
<style>
.scroller {
height: 300px;
}
.item {
height: 50px;
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
实现无限滚动加载
结合 IntersectionObserver API 或滚动事件监听实现无限滚动。

<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in visibleItems" :key="item.id">
{{ item.text }}
</div>
<div v-if="loading" class="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
loading: false,
hasMore: true
}
},
computed: {
visibleItems() {
return this.items.slice(0, this.page * 20)
}
},
methods: {
async loadMore() {
if (this.loading || !this.hasMore) return
this.loading = true
const newItems = await fetchItems(this.page)
this.items = [...this.items, ...newItems]
this.page++
this.loading = false
this.hasMore = newItems.length > 0
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target
if (scrollHeight - (scrollTop + clientHeight) < 50) {
this.loadMore()
}
}
},
mounted() {
this.loadMore()
}
}
</script>
注意事项
- 大数据量列表务必使用虚拟滚动技术
- 滚动事件监听需要节流处理
- 移动端考虑使用
touch事件优化体验 - 无限滚动需要合理设置触发阈值






