列表渲染
我们可以使用 v-for
指令基于一个数组来渲染一个列表。v-for
指令的值需要使用 item in items
形式的特殊语法,其中 items
是源数据的数组,而 item
是迭代项的别名
<template><div><p v-for="item in names">{{ item }}</p></div>
</template>
<script>
export default {data() {return {names:["百战程序员","尚学堂","IT"]}}
}
</script>
复杂数据
大多数情况,我们渲染的数据源来源于网络请求,也就是 JSON
格式
<template><div v-for="item in result"><p>{{ item.title }}</p><img :src="item.avator" alt=""></div>
</template>
<script>
export default {data() {return {result: [{"id": 2261677,"title": "鄂尔多斯|感受一座城市的璀璨夜景 感受一座城市,除了白日里的车水马龙,喧嚣繁华之","avator": "https://pic.qyer.com/avatar/002/25/77/30/200?v=1560226451",},{"id": 2261566,"title": "成都这家洞穴暗黑风咖啡厅酷毙了‼️早C晚A走起☕️ 成都天气这么热? 咖啡?人必","avator": "https://pic.qyer.com/avatar/011/07/08/69/200?v=1572185180",},{"id": 2261662,"title": "【川西新龙—措卡湖】措卡湖,意为“乱石丛中的黑色海水”,神秘小众 原汁原味。 深","avator": "https://pic.qyer.com/avatar/009/88/48/58/200?v=1507386782",},]}}
}
</script>
<style>
img{width: 50px;height: 50px;
}
</style>
v-for
也支持使用可选的第二个参数表示当前项的位置索引
<template><div><p v-for="(item,index) in names">{{ index }}:{{ item }}</p></div>
</template>
<script>
export default {data() {return {names:["百战程序员","尚学堂","IT"]}}
}
</script>
你也可以使用 of
作为分隔符来替代 in
,这更接近 JavaScript 的迭代器语法
<div v-for="item of items"></div>
v-for
与对象
你也可以使用 v-for
来遍历一个对象的所有属性
<template><div><p v-for="(value, key, index) of userInfo">{{ value }}-{{ key }}-{{ index }}</p></div>
</template>
<script>
export default {data() {return {userInfo:{name:"iwen",age:20}}}
}
</script>
实时效果反馈
1. 在Vue中,使用v-for
遍历数组,下列形式正确的是:
A item in items
B item for items
C item each items
D item map items
答案
1=>A