vue列表怎么实现
Vue 列表实现方法
使用 v-for 指令
Vue 中列表渲染主要通过 v-for 指令实现,可以遍历数组或对象。
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
}
}
</script>
遍历数组
v-for 支持获取当前项的索引。
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
</ul>
</template>
遍历对象
可以遍历对象的属性值、键名和索引。

<template>
<ul>
<li v-for="(value, key, index) in object" :key="key">
{{ index }}. {{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
object: {
title: 'Vue Guide',
author: 'Vue Team'
}
}
}
}
</script>
使用 key 属性
为每个列表项添加唯一的 key 属性,优化 Vue 的虚拟 DOM 更新性能。
<template>
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
</template>
动态列表更新
Vue 能自动检测数组变化并更新视图。但某些数组方法(如直接通过索引修改项)需要特殊处理。

// 正确方式
this.items.splice(index, 1, newItem)
// 错误方式(不会触发视图更新)
this.items[index] = newItem
列表过滤与排序
可以使用计算属性对列表数据进行处理。
computed: {
filteredItems() {
return this.items.filter(item => item.isActive)
}
}
组件中使用列表
在组件中渲染列表时,确保正确传递数据和事件。
<template>
<TodoItem
v-for="todo in todos"
:key="todo.id"
:todo="todo"
@delete="deleteTodo"
/>
</template>
性能优化
对于长列表,可使用虚拟滚动技术(如 vue-virtual-scroller)提升性能。
<template>
<RecycleScroller
class="scroller"
:items="items"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div>{{ item.name }}</div>
</RecycleScroller>
</template>






