(4) 列表渲染
1. 写法
我们可以使用 v-for
指令基于一个数组来渲染一个列表。 v-for
指令的值需要使用 item in items 形式的特殊语法其中 items 是源数据的数组,而 item 是迭代项的别名
<script>
export default{
data(){
return {
names:["张三","李四","王五"]
}
}
}
</script>
<template>
<h3>列表渲染</h3>
<p v-for="item in names">{{ item }}</p>
</template>
2. 复杂数据
大多数情况,我们渲染的数据源来源于网络请求,也就是 JSON
格式
<script>
export default{
data(){
return {
names:["张三","李四","王五"],
books:[{
"id":25739,
"title":"将进酒·君不见黄河之水天上来",
"img":"https://img.shicimingju.com/pics/item/25739.jpg",
},
{
"id":35180,
"title":"江城子·乙卯正月二十日夜记梦",
"img":"https://img.shicimingju.com/pics/item/35180.jpg",
},
{
"id":3638,
"title":"声声慢·寻寻觅觅",
"img":"https://img.shicimingju.com/pics/item/3638.jpg",
},
]
}
}
}
</script>
<template>
<h3>列表渲染</h3>
<p v-for="item in names">{{ item }}</p>
<div v-for="book in books">
<p>{{ book.title }}</p>
<img v-bind:src="book.img" alt="">
</div>
</template>
3. 位置索引
v-for
也支持使用可选的第二个参数表示当前项的位置索引
<script>
export default{
data(){
return {
names:["张三","李四","王五"],
}
}
}
</script>
<template>
<h3>列表渲染</h3>
<p v-for="(item,index) in names">{{ "item" }}-{{ index }}</p>
</template>
你也可以使用of
作为分隔符代替in
,这更接近JavaScript语法
<p v-for="(item,index) of names">{{ "items" }}-{{ index }}</p>
4. v-for
与对象
你也可以使用v-for
遍历一个对象的所有属性
<script>
export default{
data(){
return {
user:{
name:'张三',
age:'26'
}
}
}
}
</script>
<template>
<h3>列表渲染</h3>
<p v-for="(value,key,index) of user">{{ value }}-{{ key }}-{{ index }}</p>
</template>
5. 通过key管理状态
Vue默认按照“就地更新”的策略来更新通过v-for渲染的元素列表。当数据项的顺序改变时,Vue不会随之移动DOM元素的顺序,而是就地更新每个元素,确保它们在原本指定的索引位置上渲染。
为了给Vue一个提示,以便它可以跟踪每个节点的标识,从而重用和重新排序现有的元素,你需要为每个元素对应的块提供一个唯一的key
attribute:
<script>
export default{
data(){
return{
names:["张三","李四","王五"],
}
}
}
</script>
<template>
<p v-for="(item,index) of names" :key="index">{{ item }}</p>
</template>
温馨提示
key
在这里是一个通过v-bind绑定的特殊attribute
推荐在任何可行的时候为v-for提供一个key
attribute
key
绑定的值期望是一个基础类型的值,例如字符串或number类型
key的来源
请不要使用index作为key
的值,我们要确保每一条数据的唯一索引不会发生变化
<script>
export default{
data(){
return{
names:["张三","李四","王五"],
books:[{
"id":25739,
"title":"将进酒·君不见黄河之水天上来",
"img":"https://img.shicimingju.com/pics/item/25739.jpg",
},
{
"id":35180,
"title":"江城子·乙卯正月二十日夜记梦",
"img":"https://img.shicimingju.com/pics/item/35180.jpg",
},
{
"id":3638,
"title":"声声慢·寻寻觅觅",
"img":"https://img.shicimingju.com/pics/item/3638.jpg",
},
],
}
}
}
</script>
<template>
<p v-for="(item,index) of names" :key="index">{{ item }}</p>
<div v-for="(book,index) in books" :key="book.id">
<p>{{ book.title }}</p>
</div>
</template>