vue实现列表循环
Vue 列表循环的实现方法
在 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' },
{ id: 3, name: 'Item 3' }
]
}
}
}
</script>
带索引的循环
可以通过 v-for 的第二个参数获取当前项的索引:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
</ul>
</template>
对象属性循环
v-for 也可以用于遍历对象的属性:
<template>
<ul>
<li v-for="(value, key) in object" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
object: {
firstName: 'John',
lastName: 'Doe',
age: 30
}
}
}
}
</script>
使用计算属性过滤列表
可以通过计算属性对列表数据进行处理:
<template>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'fruit' },
{ id: 2, name: 'Carrot', category: 'vegetable' },
{ id: 3, name: 'Banana', category: 'fruit' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.category === 'fruit')
}
}
}
</script>
动态列表更新
Vue 会自动检测数组变化并更新视图:
<template>
<div>
<button @click="addItem">Add Item</button>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
nextId: 3
}
},
methods: {
addItem() {
this.items.push({
id: this.nextId++,
name: `Item ${this.nextId - 1}`
})
}
}
}
</script>
性能优化注意事项
- 始终为
v-for提供唯一的:key属性,帮助 Vue 识别节点 - 避免在模板中使用复杂表达式,优先使用计算属性
- 对于大型列表,考虑使用虚拟滚动技术
这些方法涵盖了 Vue 中列表循环的主要使用场景,可以根据具体需求选择适合的实现方式。







