v-for的使用

it2026-02-15  6

v-for的使用

v-for用于遍历数组和对象。

<div id="app"> <!-- (参1,参2,参3)这几个参数分别对应谁?谁更重要就把谁放在前面,即value,key,index --> <!-- 遍历数组中的内容 --> <h3 v-for="item in arg" :key="item">{{item}}</h3> <!-- 遍历数组中的内容并加上index --> <h3 v-for="(item,index) in arg">{{index}}-{{item}}</h3> <!-- 遍历对象中的value --> <h3 v-for="item in oriend"> {{item}}</h3> <!-- 遍历对象的key和value --> <h3 v-for="(value,key) in oriend">{{key}}:--{{value}}</h3> <!-- 遍历对象的key和value并加上index --> <h3 v-for="(value,key,index) in oriend">{{index+1}}{{key}}:--{{value}}</h3> </div> <script> const vm = new Vue({ el: '#app', data: { arg: ['111', '222', '333'], oriend: { name: 'lucy', age: 20, sex: "female" } }, methods: {}, computed: {} });

注意官方建议在使用v-for时加上绑定key以提高插入数据等操作的性能,如下图所示

key需要一一对应才有意义,为方便使用,可以绑定为item(数组值或者对象的value值),如:

{{item}}

.key不能为设置为index(索引值),index在一直变化,不能做到一一对应。

最新回复(0)