vue中如何实现循环
循环渲染列表数据
在Vue中,使用v-for指令实现循环渲染。基本语法为v-for="(item, index) in items",其中items是数据源数组,item是当前遍历的元素,index是可选索引值。
<template>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{{ index }} - {{ fruit }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Orange']
}
}
}
</script>
循环渲染对象属性
v-for也可以遍历对象的属性,语法为v-for="(value, key, index) in object"。
<template>
<ul>
<li v-for="(value, key) in user" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
user: {
name: 'John',
age: 30,
gender: 'male'
}
}
}
}
</script>
使用范围循环
Vue允许通过数字范围进行循环,语法为v-for="n in 10",会从1循环到10。
<template>
<div>
<span v-for="n in 5" :key="n">{{ n }}</span>
</div>
</template>
维护状态的关键key
为每个循环元素添加唯一的key属性,帮助Vue高效更新DOM。避免使用索引作为key,除非列表是静态的。
<template>
<div v-for="item in items" :key="item.id">
{{ item.name }}
</div>
</template>
在组件上使用v-for
在自定义组件上使用v-for时,需要显式传递数据作为props。
<template>
<my-component
v-for="(item, index) in items"
:key="item.id"
:item="item"
:index="index"
/>
</template>
条件循环组合
v-for可以与v-if一起使用,但Vue3推荐使用计算属性过滤数据,而不是在同一元素上同时使用这两个指令。
<template>
<ul>
<li v-for="fruit in filteredFruits" :key="fruit">
{{ fruit }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Orange']
}
},
computed: {
filteredFruits() {
return this.fruits.filter(fruit => fruit !== 'Banana')
}
}
}
</script>






