var ss = new Vue({
'el': '#App',
data: {
products:[
{id:1,name:"iphoneXS",num:0,price:100},
{id:2,name:"Huawei20",num:0,price:80},
{id:3,name:"xiaomi8",num:0,price:50}
],
selectAll:false,
selectAllDate:[],
},
// computed:{
// total(){
// this.total = 0;
// this.products.forEach((v)=>{
// // debugger
// this.total += v.price*v.num
// } )
// return total
// }
// },
methods: {
allCheck(e){
e = e||event
//alert(e.currentTarget.checked) //true false
if(e.currentTarget.checked){
this.products.forEach((v)=>{
this.selectAllDate.push(v.id)
})
}else{
this.selectAllDate=[]
}
// debugger
},
//每个checkebox元素
Iselect(id){
// this.products.forEach((v)=>{
// alert(v.length)
// })
// alert(this.selectAllDate.length)
var res = this.selectAllDate.indexOf(id);
res == -1 ? this.selectAllDate.push(id) : this.selectAllDate.splice(res,1) //注意第一个是id,第二个res
this.selectAll = this.selectAllDate.length == this.products.length ? true : false
},
add(k){
this.products[k].num++ //this.products指的就是data里面的products
},
ajj(k){
this.products[k].num--
if( this.products[k].num<=0){
this.products.splice(k,1) //误区写成this.products[k].splice(k,1)
}
},
del(k){
this.products.splice(k,1)
},
check(){
if(this.checked == this.products.length){
this.checked = true
}else{
this.checked = false
}
},
// 行不通
//
// mounted(){
// this.totalPrice()
// },
// totalPrice(){
// this.total=0;
// // v就是item的意思 把good的数据给了参数v
// this.products.forEach((v)=>{
// // debugger //用debugger,就知道不能写在methods里面,因为num加的时候数据并没有更新,除非用$emit输入完了就触发方法
// // alert(v.num)
// this.total += v.num*v.price;
// })
// },
// ajj(k){
// this.products[k].num--
// if( this.products[k].num<=0){
// this.products[k].num=0
// }
// },
},
computed:{
total(){ // 这个total就是total属性
var total=0 //var total 不是this.total
this.products.forEach((v,k)=>{
if(this.selectAllDate.indexOf(v.id)!=-1){
total += v.num*v.price
}
})
return total
},
}
});
<div id="App">
<template v-if='products.length == 0'>
购物车为空
</template>
<template v-else>
<table>
<tr>
<th><input type="checkbox" v-model="selectAll" @click="allCheck"></th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>操作</th>
</tr>
<tr v-for="(item,k) in products">
<td><input type="checkbox" :checked="selectAllDate.indexOf(item.id) != -1" @click="Iselect(item.id)"></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<input type='button' value="+" @click="add(k)">
<input type="text" name="" id="" style="width:30px" v-model="item.num"/>
<input type='button' value="-" @click="ajj(k)">
</td>
<td>
<button @click="del(k)">删除</button>
</td>
</tr>
</table>
</template>
<div> 总计:{{total}}元</div>
</div>