X
XiaoSong
V1
2023/01/28阅读:23主题:默认主题
列表渲染
v-for
使用
v-for
指令循环一个数组来渲染数组中的内容,使用起来的感觉和for
循环类似。使用的格式是:v-for="item in arrList"
,arrList
是数据源,item
是迭代的项的名称,可以随意起名。
<div class="item" v-for="item in dataList">
{{ item.name }}
</div>
const dataList = ref([
{name: 'Xiaomi', price: 4999, goodsId: '10'},
{name: 'apple', price: 6999, goodsId: '18'}
])
最终渲染的结果:
使用可选的第二参数
index
,表示当前项的索引
<div class="item" v-for="(item, index) in dataList">
{{ item.name }}
</div>
v-for
块中可以访问父作用域中的属性和变量。这里用JavaScript代码举例:
const brand = 'brand'
const arrList = [/*....*/]
arrList.forEach((item, index) => {
// 可以访问外层的 `brand`
// 而 `item` 和 `index` 只在这个作用域可用
})
对于多级嵌套的
v-for
<li v-for="item1 in dataList">
<span v-for="childItem in item1.goodsClass">
{{ childItem}}
</span>
</li>
const dataList = ref([
{name: 'Xiaomi', price: 4999, goodsId: '10', goodsClass: [/* .... */]},
{name: 'apple', price: 6999, goodsId: '18', goodsClass: [/* .... */]}
])
使用
of
代替in
也可以
<div v-for="item of dataList"></div>
作者介绍
X
XiaoSong
V1