概述

v-for=”(value, index) in 数组名”

第一个参数表示遍历时的对象,第二个参数则代表下标(参数值可以根据自己的需求设置)

参考代码

使用了数组下标设置数组的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<div id="app">
<div>
<h3 style="color: red">总价:{{calculatePriceTotal}}</h3>
<h3 v-for="(value, index) in snacks">
<div style="background: beige">
<p style="color: blue">数组下标:{{index}}&nbsp;&nbsp;对象:{{value}}</p>
<p>编号:{{value.id}}&nbsp;&nbsp;名称:{{value.name}}&nbsp;&nbsp;价格:{{value.price}}&nbsp;&nbsp;数量:{{value.num}}&nbsp;&nbsp;当前商品总价:{{value.num * value.price}}</p>
<div style="margin-top: 5px">
<input type="text" v-model="value.num">
<button @click="addNum(index)">加1</button>
<button @click="lessNum(index)">减1</button>
</div>
</div>
</h3>
</div>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
snacks: [
{id: 1, name: '零食1', price: 11, num: 3},
{id: 2, name: '零食2', price: 5, num: 2},
{id: 3, name: '零食3', price: 8, num: 6}
]
},
methods: {
addNum: function (index) {
this.snacks[index].num++;
},
lessNum: function (index) {
if (this.snacks[index].num > 0) {
this.snacks[index].num--;
}
}
},
computed: {
calculatePriceTotal: function () {
let total = 0;
for (let i = 0; i < this.snacks.length; i++) {
total += parseInt(this.snacks[i].num) * parseInt(this.snacks[i].price);
}
return total;
}
}
})
</script>

img