vue实现循环
在 Vue 中实现循环
Vue 提供了 v-for 指令来实现循环渲染数据列表。v-for 可以遍历数组、对象或数字范围。
遍历数组
通过 v-for 可以遍历数组,并为每个元素渲染模板。语法为 item in items 或 (item, index) in items。

<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }} - {{ index }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Apple', 'Banana', 'Orange']
}
}
}
</script>
遍历对象
v-for 也可以遍历对象的属性,语法为 (value, key, index) in object。
<template>
<ul>
<li v-for="(value, key, index) in user" :key="key">
{{ key }}: {{ value }} ({{ index }})
</li>
</ul>
</template>
<script>
export default {
data() {
return {
user: {
name: 'John',
age: 30,
city: 'New York'
}
}
}
}
</script>
遍历数字范围
v-for 可以渲染一个数字范围内的内容,语法为 n in 10(从 1 开始)。

<template>
<ul>
<li v-for="n in 5" :key="n">
{{ n }}
</li>
</ul>
</template>
使用 key 属性
在 v-for 中,建议为每个循环项提供一个唯一的 key 属性,以便 Vue 高效更新 DOM。通常使用 id 或其他唯一标识符。
<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: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
}
}
</script>
结合条件渲染
v-for 可以和 v-if 结合使用,但需要注意优先级问题。v-for 的优先级高于 v-if,因此推荐使用计算属性过滤数据。
<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', isActive: true },
{ id: 2, name: 'Banana', isActive: false },
{ id: 3, name: 'Orange', isActive: true }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.isActive)
}
}
}
</script>
通过以上方法,可以在 Vue 中灵活实现循环渲染数据的功能。






