1.点击全选按钮,修改每个店铺选中状态,修改每个店铺下面每个商品选中状态。
2.点击店铺按钮,修改当前店铺下面每个商品的选中状态,如果所有店铺都选中,修改全选按钮选中状态
3.点击商品按钮,如果当前店铺下面所有商品都选中,修改店铺的选中状态,如果所有店铺都选中,修改全选按钮选中状态
<template>
<div class="box">
<div class="header">
<input
type="checkbox"
id="selectAllShop"
:checked="all"
@change="checkAll"
/>
<label for="selectAllShop">全选</label>
</div>
<div v-for="s in shops" :key="s.shopId">
<div class="shop-name">
<input
type="checkbox"
:checked="s.selected"
@change="checkShop($event, s)"
/>
<span>店铺:{{ s.shopName }}</span>
</div>
<div class="product-list">
<!-- 商品 -->
<div class="product" v-for="p in s.products" :key="p.id">
<div>
<input
type="checkbox"
:checked="p.selected"
@change="check($event, p, s)"
/>
<span>商品:{{ s.shopName }}</span>
</div>
</div>
</div>
</div>
<div class="foot">
已选商品<span>{{ totalCount }}</span> 件 合计金额:<span>{{
totalPrice
}}</span>
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
all: false,
shops: [],
};
},
created() {
this.getShopcar();
},
methods: {
getShopcar() {
this.$axios.get("/data/shopcart.json").then((res) => {
this.shops = res.data.cart;
});
},
checkShop(e, s) {
s.selected = e.target.checked; //修改当前店铺的选中状态
s.products.forEach((item) => {
item.selected = e.target.checked; //修改当前店铺下每个商品的选中状态
});
var count = this.shops.filter((item) => item.selected).length;
this.all = count == this.shops.length; //判断所有店铺,是否都选中,如果都选中,那么修改全选按钮选中
},
check(e, p, s) {
p.selected = e.target.checked; //修改当前商品的选中状态
var selectProductCount = s.products.filter(
(item) => item.selected
).length;
s.selected = selectProductCount == s.products.length; //判断当前店铺,是否都选中,如果都选中,那么修改店铺按钮选中
var count = this.shops.filter((item) => item.selected).length;
this.all = count == this.shops.length; //判断所有店铺,是否都选中,如果都选中,那么修改全选按钮选中
},
checkAll(e) {
this.all = e.target.checked; //修改全选按钮的选中状态
this.shops.forEach((item) => {
item.selected = e.target.checked; //修改店铺的选中状态
item.products.forEach((it) => {
it.selected = e.target.checked; //修改商品的选中状态
});
});
},
},
computed: {
totalCount() {
var res = 0;
this.shops.forEach((item) => {
item.products.forEach((it) => {
if (it.selected) {
res += it.count;
}
});
});
return res;
},
totalPrice() {
var res = 0;
this.shops.forEach((item) => {
item.products.forEach((it) => {
if (it.selected) {
res += it.count * it.price;
}
});
});
return res;
},
},
};
</script>