使用vue写出简单的购物车,供大家参考,具体内容如下
代码:
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
|
// An highlighted block
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >Document</ title >
< style >
.cl{
border: 1px solid black;
width: 300px;
margin: 30px;
padding: 15px;
}
</ style >
</ head >
< body >
< div id = "app" >
< div class = "cl" v-for = "(item,index) in items" >
< h4 >{{item.sname}}</ h4 >
< button @ click = "item.sum==0?item.sum==0:item.sum--" >-</ button >
< span >{{item.sum}}</ span >
< button @ click = "item.sum++" >+</ button >
< span >{{item.sprice}}元/斤</ span >
</ div >
< table >
< tr >
< th >选择</ th >
< th >商品名</ th >
< th >商品数量</ th >
< th >商品价格</ th >
</ tr >
< tr v-for = "(item,index) in items" >
< td >< input type = "checkbox" :checked = "item.isSelect" @ click = "item.isSelect=!item.isSelect" ></ td >
< td >{{item.sname}}</ td >
< td >{{item.sum}}</ td >
< td >{{item.sprice*item.sum}}</ td >
</ tr >
< tr >
< td >< input type = "checkbox" @ click = "selectProduct(isSelectAll)" :checked = "isSelectAll" >全选</ tf >
< td >合计</ tf >
< td >{{total.totalNum}}</ tf >
< td >{{total.totalPrice}}</ tf >
</ tr >
</ table >
</ div >
< script src = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" ></ script >
< script >
new Vue({
el:'#app',
data:{
items:[
{
'sname':'苹果',
'sum':1,
'sprice':'10',
},
{
'sname':'香蕉',
'sum':1,
'sprice':'12',
},
{
'sname':'橘子',
'sum':1,
'sprice':'8',
},
]
},
methods:{
selectProduct:function(_isSelect){
for(var i=0 ,len=this.items.length;i< len ;i++){
this.items[i].isSelect=!_isSelect;
}
},
},
computed:{
isSelectAll:function(){
return this.items.every(function(val){return val.isSelect})
},
total:function(){
var prolist = this .items.filter(function(val){return val.isSelect});
totalpri = 0 ;
totalnum = 0 ;
for (var i = 0 ;i<prolist.length;i++){
totalpri+=prolist[i].sprice*prolist[i].sum;
totalnum+=prolist[i].sum
}
return{totalNum:totalnum,totalPrice:totalpri}
}
},
mounted:function(){
var _this =this;
this.items.map(function(item){
_this.$set(item,'isSelect',false)
})
}
})
</script>
</ body >
</ html >
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_44846765/article/details/112257578