vue如何实现循环
Vue 中实现循环的方法
Vue 提供了 v-for 指令来实现循环渲染,可以遍历数组、对象或数字范围。
遍历数组
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
</li>
</ul>
items 是数据数组,item 是当前遍历的元素,index 是当前索引。:key 是必须的,用于 Vue 的虚拟 DOM 优化。
遍历对象
<ul>
<li v-for="(value, key, index) in object" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
value 是属性值,key 是属性名,index 是当前索引。
遍历数字范围
<ul>
<li v-for="n in 10" :key="n">
{{ n }}
</li>
</ul>
这会渲染数字 1 到 10。

使用 v-for 和 v-if
避免在同一元素上同时使用 v-for 和 v-if,因为 v-for 的优先级更高。可以在外层使用 <template> 标签:
<template v-for="item in items">
<li v-if="item.isActive" :key="item.id">
{{ item.name }}
</li>
</template>
维护状态
为每个循环项添加唯一的 :key,帮助 Vue 识别节点,提高渲染效率:

<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
在组件中使用 v-for
在自定义组件中使用 v-for 时,需要显式传递数据:
<my-component
v-for="(item, index) in items"
:item="item"
:index="index"
:key="item.id"
></my-component>
数组更新检测
Vue 能检测到数组的以下变更方法并触发视图更新:
push()pop()shift()unshift()splice()sort()reverse()
对于非变更方法(如 filter()、concat()、slice()),可以用新数组替换旧数组:
this.items = this.items.filter(item => item.isActive)
通过以上方法,可以在 Vue 中灵活实现各种循环需求。






