console
var vm = new Vue({
el: "#cart",
data: {
cartitem: [{
id: 001,
name: 'iphone5s',
quantity: 1,
price: 4000,
state: true
}, {
id: 002,
name: 'iphone5',
quantity: 1,
price: 3000,
state: true
}, {
id: 003,
name: 'imac',
quantity: 1,
price: 7000,
state: true
}, {
id: 004,
name: 'ipad',
quantity: 1,
price: 6000,
state: true
}]
},
computed: {
totalprice: function() {
var totalprice = 0;
var _this = this;
_this.cartitem.forEach(function(v, i) {
v.state == true ? totalprice += Number(_this.cartitem[i].price) * Number(_this.cartitem[i].quantity) : '';
});
return totalprice.toFixed(2);
},
checkall: function() {
var flag = true;
this.cartitem.forEach(function(v, i) {
if(v.state == false) {
flag=false;
return false;
}
});
return flag;
},
},
methods: {
add: function(i) {
vm.cartitem[i].quantity++;
},
reduce: function(i) {
if(vm.cartitem[i].quantity <= 1) {
alert("不能再少了亲~~");
return false;
} else {
vm.cartitem[i].quantity--;
}
},
selectall: function() {
var flag = true;
vm.cartitem.forEach(function(v,i){
if(v.state==false){
flag=false;
return false;
}
});
if(!flag){
vm.cartitem.forEach(function(v,i){
v.state=true;
});
}else{
vm.cartitem.forEach(function(v,i){
v.state=false;
});
}
},
remove: function(index) {
vm.cartitem.splice(index, 1);
},
empty: function() {
vm.cartitem.splice(0, vm.cartitem.length);
},
},
});
<div id="cart">
<table v-if="cartitem.length!=0">
<thead>
<tr>
<th></th>
<th>id</th>
<th>name</th>
<th>quantity</th>
<th>price</th>
<th>allprice</th>
<th>delect</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in cartitem">
<td>
<input type="checkbox" v-model="item.state">
</td>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<button @click="reduce(index)">-</button>
<input type="number" :value="item.quantity" disabled="disabled" />
<button @click="add(index)">+</button>
</td>
<td>{{item.price}}</td>
<td>{{item.price*item.quantity}}</td>
<td><button type="button" @click="remove(index)">delect</button></td>
</tr>
<tr>
<td colspan="2">
<input type="checkbox" @click="selectall" :checked="checkall">全选
</td>
<td>合计:</td>
<td>{{totalprice}}</td>
<td></td>
<td colspan="3">
<button type="button" @click="empty()">清空购物车</button>
</td>
</tr>
</tbody>
</table>
<p v-else>
您的购物车为空
</p>
</div>