vue列表实现
Vue 列表实现方法
在 Vue 中实现列表渲染通常使用 v-for 指令,结合数组或对象数据动态生成 DOM 元素。以下是几种常见的实现方式:
基础列表渲染
使用 v-for 指令遍历数组,生成列表项。item 是当前元素,index 是可选索引。
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
]
}
}
}
</script>
对象遍历
v-for 也可以遍历对象的属性,参数顺序为 (value, key, index)。
<template>
<ul>
<li v-for="(value, key) in object" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
object: {
title: 'Vue Guide',
author: 'Vue Team',
published: '2021'
}
}
}
}
</script>
使用组件渲染列表
将列表项封装为可复用的组件,通过 props 传递数据。
<template>
<ul>
<list-item
v-for="(item, index) in items"
:key="item.id"
:item="item"
/>
</ul>
</template>
<script>
import ListItem from './ListItem.vue'
export default {
components: { ListItem },
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
}
}
</script>
条件渲染与列表结合
通过 v-if 或计算属性实现条件筛选后的列表渲染。
<template>
<ul>
<li v-for="item in activeItems" :key="item.id">
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1', isActive: true },
{ id: 2, text: 'Item 2', isActive: false }
]
}
},
computed: {
activeItems() {
return this.items.filter(item => item.isActive)
}
}
}
</script>
性能优化
对于大型列表,可通过虚拟滚动(如 vue-virtual-scroller)减少 DOM 节点数量。

<template>
<RecycleScroller
class="scroller"
:items="largeList"
: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 {
largeList: Array(1000).fill().map((_, i) => ({
id: i,
text: `Item ${i}`
}))
}
}
}
</script>
注意事项
- key 属性:必须为每项提供唯一
key,通常使用 ID 而非索引,避免渲染问题。 - 数组更新:直接修改数组(如
this.items[0] = newValue)不会触发视图更新,应使用Vue.set或数组方法(push,splice等)。 - 性能监控:超长列表需配合虚拟滚动或分页,避免内存问题。






