学习Vue(五)

Vue的第一个练习,感觉跟jquery比,少了很多逻辑操作

html

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车练习</title>
<link rel="stylesheet" href="style.css">

</head>
<body>

<div id="app">
<template v-if="list.length">
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</tr>

<tr v-for="(item,index) in list">
<td>{{index}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="myReduce(index)" :disabled="item.count === 1">-</button>
{{item.count}}
<button @click="myAdd(index)">+</button>
</td>
<td><button @click="myRemove(index)">移除</button></td>
</tr>
</table>
<div>总价:{{totalPrice}}</div>
</template>
<div v-else>购物车为空</div>
</div>


<script src="../../js/vue.js"></script>
<script src="index.js"></script>


</body>
</html>

js

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
48
49
50
var app = new Vue({
el:"#app",
data:{
list:[
{
id:1,
name:"iphone 7",
price:6187,
count:2
},
{
id:2,
name:"iphone 8",
price:6188,
count:2
},
{
id:3,
name:"iphone 9",
price:6189,
count:3
}
]
},
computed:{
totalPrice: function () {
var total = 0;
for(var i=0;i<this.list.length;i++){
var item = this.list[i];
total += item.price * item.count;
}

return total.toString();

}
},
methods:{
myReduce:function (index) {
if(this.list[index].count === 1) return;
this.list[index].count--;
},
myAdd: function (index) {
this.list[index].count++;

},
myRemove:function (index) {
this.list.splice(index, 1);
}
}
});