水果购物车

从现在开始做Vue2的第二个案例。

上图

屏幕截图 2024-04-11 205330

因为有些图片资源丢失了,所以图片的那列就直接改成写名字就好

代码

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水果购物车</title>
<script src="../fronttools/vue.js"></script>
</head>
<body>
<div id="app">
<table border="2" cellspacing="0" style="width: 500px;">

<tr>
<th>选中</th>
<th>名称</th>
<th>单价</th>
<th>个数</th>
<th>小计</th>
<th>操作</th>
</tr>
<tbody v-if="arr.length>0">
<tr style="text-align: center;" v-for="(it, index) in arr" :key="index" >
<td><input type="checkbox" v-model="it.checked"></td>
<td>{{it.name}}</td>
<td>{{it.price}}</td>
<td>
<button @click="dec(it.id)" :disabled="it.num<=1" >-</button>{{it.num}}<button @click="add(it.id)">+</button>
</td>
<td>{{it.price*it.num}}</td>
<td><button style="background-color: rgb(239, 124, 124);" @click="del(it.id)">删除</button></td>
</tr>

</tbody>
<tbody v-else>
<td colspan="6" style="text-align: center; height: 100px;">购物车暂时无商品</td>
</tbody>
</table>
<div style="width: 500px;">
<input type="checkbox" v-model="choose">全选 <span style="float: right;">总计:(¥{{amount}}) <button @click="hh">清空购物车{{countn}}</button></span>
</div>

</div>
</body>
<script>
const addd=[
{id:1,checked:true,name: "菠萝",price: 6,num:1},
{id:2,checked:true,name: "西瓜",price: 4,num:1},
{id:3,checked:true,name: "香蕉",price: 6,num:1},
]
new Vue({
el: "#app",
data:{

arr:JSON.parse(localStorage.getItem('list'))|| addd

},
methods: {
dec(id1){
const fruit=this.arr.find(it=>it.id===id1);
fruit.num--;
},
add(id){
const fruit=this.arr.find(it=>it.id===id);
fruit.num++;
},
del(a){
this.arr=this.arr.filter(aa=>aa.id!==a);
},
hh(){
this.arr=[]
}
},
computed:{
choose:{
get(va){
return this.arr.every(a=>a.checked)
},
set(va){
this.arr.forEach(element => {
element.checked=va
});
}
},
countn(){
return this.arr.reduce((sum,it)=>{
if(it.checked){
return sum+it.num
}else return sum
},0)
},
amount(){
return this.arr.reduce((sum,it)=>{
if(it.checked){
return sum+it.num*it.price
}else return sum
},0)
}
},
watch:{
arr:{
deep :true,
handler (newit){
/* 将变化后的数据存到本地 */
localStorage.setItem('list',JSON.stringify(newit))
}
}
}
})
</script>
</html>
更新于

请我喝[茶]~( ̄▽ ̄)~*

罗梓丰 微信支付

微信支付

罗梓丰 支付宝

支付宝