Vue实现购物车场景下的应用(2)

选择购物车时执行 setAllChecked,此时选择所有商品和店铺
选择店铺时执行 setGoodChecked,此时选择该店铺下所有商品
选择商品时执行 setShopChecked
    当商品 checked 为 false 时,取消选择当前店铺
    当商品 checked 为 true 时,判断当前店铺是否选择了所有商品,是则选择当前店铺,否则取消选择当前店铺

二、删除商品

<input type="button" value="删除" @click="deleteGood(shop,goodI,list,shopI)">
methods: {
 deleteGood: function(shop,goodI,list,shopI) {
  shop.goods.splice(goodI, 1);
  if (shop.goods.length==0) {
   list.splice(shopI, 1);
  }
 }
}

全部代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的购物车</title>
<script src="vue.min.js"></script>
</head>
<body class="app">
<input type="checkbox" v-if="list.length" v-model="checkedAll" @change="setAllChecked($event)">
<div v-for="(shopI, shop) in list">
<input type="checkbox" v-model="shop.checked" @change="setGoodChecked(shop)">
<div v-for="(goodI, good) in shop.goods">
<input type="checkbox" v-model="good.checked" @change="setShopChecked(good, shop)">
<span v-html="good.name"></span>
<span v-html="good.age"></span>
<input type="button" value="删除" @click="deleteGood(shop,goodI,list,shopI)">
</div>
</div>
</body>
<script>
var _list = [{
checked: false,
goods: [{
name: "商品1",
money: 23,
checked: false
}]
}, {
checked: false,
goods: [{
name: "商品2",
money: 20,
checked: false
}, {
name: "商品3",
money: 30,
checked: false
}]
}];
var vue = new Vue({
el: '.app',
data: {
list: _list
},
computed: {
checkedAll: function() {
return this.checkedShopsCount == this.list.length;
},
checkedShopsCount: function() {
var i = 0;
this.list.forEach(function(item) {
if (item.checked == true) i++;
});
return i;
}
},
methods: {
setGoodChecked: function(shop) {
shop.goods.forEach(function(good) {
good.checked = shop.checked;
});
},
setShopChecked: function(good, shop) {
if (!good.checked) {
shop.checked = false;
} else {
shop.checked = !shop.goods.find(function(good) {
return !good.checked;
});
}
},
setAllChecked: function(e) {
this.list.forEach(function(shop) {
shop.checked = e.target.checked;
shop.goods.forEach(function(good) {
good.checked = e.target.checked;
});
});
},
deleteGood: function(shop, goodI, list, shopI) {
shop.goods.splice(goodI, 1);
if (shop.goods.length == 0) {
list.splice(shopI, 1);
}
}
}
});
</script>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。