vue实现for循环
Vue 中实现 for 循环的方法
在 Vue 中,通常使用 v-for 指令来实现循环渲染列表数据。以下是几种常见的实现方式:
基本数组循环
通过 v-for 遍历数组,item 为当前项,index 为索引(可选):
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ index }}: {{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ name: 'Apple' },
{ name: 'Banana' },
{ name: 'Cherry' }
]
}
}
}
</script>
对象属性循环
遍历对象的属性,value 为属性值,key 为属性名(可选):

<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: 'Evan You',
published: '2014'
}
}
}
}
</script>
数字范围循环
直接遍历数字范围(从 1 开始):
<template>
<span v-for="n in 5" :key="n">{{ n }}</span>
</template>
使用 key 的注意事项
为维护内部组件状态,建议始终为 v-for 提供唯一的 key 属性:

<div v-for="item in items" :key="item.id">
<!-- 内容 -->
</div>
性能优化
当处理大型列表时,可结合 <template> 减少 DOM 节点:
<template v-for="item in items" :key="item.id">
<div>{{ item.title }}</div>
<div>{{ item.content }}</div>
</template>
与 v-if 一起使用
不推荐在同一元素上同时使用 v-for 和 v-if。若需条件过滤,应改用计算属性:
computed: {
filteredItems() {
return this.items.filter(item => item.isActive)
}
}






