vue实现纵向列表
实现纵向列表的基本方法
使用 Vue 实现纵向列表可以通过 v-for 指令动态渲染数组数据。基本结构包括一个外层容器和循环生成的列表项。
<template>
<div class="list-container">
<div v-for="(item, index) in items" :key="index" class="list-item">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
]
};
}
};
</script>
<style>
.list-container {
display: flex;
flex-direction: column;
gap: 10px;
}
.list-item {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>
动态加载更多数据
对于长列表,可以通过监听滚动事件实现无限滚动加载。使用 @scroll 事件和计算逻辑判断是否触底。
<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="(item, index) in items" :key="index" class="list-item">
{{ item.text }}
</div>
<div v-if="loading" class="loading">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
loading: false,
page: 1
};
},
mounted() {
this.fetchData();
},
methods: {
async fetchData() {
this.loading = true;
const newItems = await api.fetchItems(this.page);
this.items = [...this.items, ...newItems];
this.page++;
this.loading = false;
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
if (scrollHeight - (scrollTop + clientHeight) < 50 && !this.loading) {
this.fetchData();
}
}
}
};
</script>
使用第三方库优化性能
对于超长列表(如上千项),建议使用虚拟滚动库(如 vue-virtual-scroller)减少 DOM 节点数量。

安装依赖:
npm install vue-virtual-scroller
示例代码:

<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="item">
{{ item.text }}
</div>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller },
data() {
return {
items: [] // 需包含唯一id字段
};
}
};
</script>
<style>
.scroller {
height: 400px;
}
.item {
height: 50px;
padding: 10px;
}
</style>
添加动画效果
通过 Vue 的过渡组件实现列表项入场动画。
<template>
<div class="list">
<transition-group name="fade">
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</transition-group>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.item {
margin: 5px 0;
}
</style>
响应式布局适配
结合 CSS Grid 或媒体查询实现不同屏幕尺寸下的列表布局调整。
.list-container {
display: grid;
grid-template-columns: 1fr;
gap: 15px;
}
@media (min-width: 768px) {
.list-container {
grid-template-columns: repeat(2, 1fr);
}
}






