简易购物车功能(无任何布局 主要是功能)
- 数量的加减
- 商品的总价钱
- 全选与全不选
- 删除(全选、价格 受影响)
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="box">
全选:<input type="checkbox" @click="handleAllChecked($event)" v-model="isAllChecked"/>
<ul>
<li v-for="data,index in list" :key="data.id" style="overflow: hidden;">
<input type="checkbox" :value="data" v-model="checkgroup" style="float: left;"
@change="handleItemChange()"/>
<div style="float: left;">
<div>{{data.name}}</div>
<div>价格:{{data.price}}</div>
<!-- <div>数量:{{data.number}}</div> -->
</div>
<div style="float: left;margin-left: 20px;">
<button @click="handleDel(data)">-</button>
{{data.number}}
<button @click="data.number++">+</button>
</div>
<div style="float: right;">
<button @click='handleRemove(index,data.id)'>remove</button>
</div>
</li>
</ul>
{{checkgroup}}
<p>总金额:{{ getSum() }}</p>
</div>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
data:{
name:"kerwin",
checkgroup:[],
isAllChecked:false,
list:[
{
name:"商品1",
price:10,
number:1,
id:"1",
},
{
name:"商品2",
price:20,
number:2,
id:"2",
},
{
name:"商品3",
price:30,
number:3,
id:"3",
}
]
},
methods: {
// 每个chekcbox 改变触发, 判读数组的长度与list长度
handleItemChange(){
console.log(this.checkgroup.length)
if(this.checkgroup.length===this.list.length && this.list.length !== 0 ){
//全选chekcbox勾上
this.isAllChecked = true
}else{
// 取消checkbox勾选
this.isAllChecked = false
}
},
//全选按钮处理
handleAllChecked(evt){
if(evt.target.checked){
//全选中
this.checkgroup = this.list
}else{
//全不选中
this.checkgroup = []
}
},
//商品减少
handleDel(data){
data.number--
if(data.number===0){
data.number =1
}
},
//计算总金额
getSum(){
var sum = 0;
for(var i in this.checkgroup){
sum += this.checkgroup[i].price*this.checkgroup[i].number
}
return sum
},
//删除数据
handleRemove(index,id) {
//list
this.list.splice(index,1)
//checkgroup
this.checkgroup =this.checkgroup.filter(item => item.id !== id)
this.handleItemChange()
}
},
})
</script>