vue实现滚动显示列表
使用 v-for 和 CSS 实现滚动列表
在 Vue 中,可以通过 v-for 渲染列表数据,结合 CSS 的 overflow 和滚动样式实现滚动效果。
<template>
<div class="scroll-container">
<div v-for="(item, index) in list" :key="index" class="list-item">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
};
}
};
</script>
<style>
.scroll-container {
height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
}
.list-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
使用 setInterval 实现自动滚动
通过 JavaScript 定时器控制滚动容器的 scrollTop 属性,实现自动滚动效果。

<template>
<div ref="scrollContainer" class="scroll-container">
<div v-for="(item, index) in list" :key="index" class="list-item">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'],
scrollInterval: null
};
},
mounted() {
this.startAutoScroll();
},
beforeDestroy() {
this.stopAutoScroll();
},
methods: {
startAutoScroll() {
this.scrollInterval = setInterval(() => {
const container = this.$refs.scrollContainer;
if (container.scrollTop >= container.scrollHeight - container.clientHeight) {
container.scrollTop = 0;
} else {
container.scrollTop += 1;
}
}, 50);
},
stopAutoScroll() {
if (this.scrollInterval) {
clearInterval(this.scrollInterval);
}
}
}
};
</script>
使用第三方库 vue-virtual-scroller 优化长列表
对于长列表,推荐使用 vue-virtual-scroller 实现高效滚动渲染,避免性能问题。
安装依赖:

npm install vue-virtual-scroller
示例代码:
<template>
<RecycleScroller
class="scroller"
:items="list"
: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 {
list: Array.from({ length: 1000 }, (_, i) => ({
id: i,
text: `Item ${i + 1}`
}))
};
}
};
</script>
<style>
.scroller {
height: 300px;
}
.item {
height: 50px;
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
监听滚动事件实现懒加载
通过监听滚动事件,在接近底部时动态加载更多数据,适合分页场景。
<template>
<div
ref="scrollContainer"
class="scroll-container"
@scroll="handleScroll"
>
<div v-for="(item, index) in list" :key="index" class="list-item">
{{ item }}
</div>
<div v-if="loading" class="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
loading: false,
page: 1
};
},
mounted() {
this.loadData();
},
methods: {
loadData() {
this.loading = true;
// 模拟异步加载数据
setTimeout(() => {
const newItems = Array.from(
{ length: 20 },
(_, i) => `Item ${this.list.length + i + 1}`
);
this.list = [...this.list, ...newItems];
this.page++;
this.loading = false;
}, 1000);
},
handleScroll() {
const container = this.$refs.scrollContainer;
const threshold = 100;
if (
container.scrollTop + container.clientHeight >=
container.scrollHeight - threshold &&
!this.loading
) {
this.loadData();
}
}
}
};
</script>






