<label><input type="checkbox" v-model="chkAll" />全选</label>
<ul>
<li v-for="item in carts">
<label
><input
type="checkbox"
v-model="item.chk"
/>{{item.product.name}}</label
>
;单价:{{item.product.price}}X<button
@click="item.amount>1?item.amount--:null"
>
-</button
>{{item.amount}}<button @click="item.amount++">+</button>
</li>
</ul>
<hr />
<p>总价:{{sumPrice}}</p>
data() {
return {
carts: [
{
id: 1,
amount: 2,
chk: false,
product: {
id: 101,
name: "AirPods Pro 2",
price: 1899,
},
},
{
id: 2,
amount: 1,
chk: false,
product: {
id: 102,
name: "IPhone 14 pro",
price: 7999,
},
},
{
id: 3,
amount: 2,
chk: false,
product: {
id: 103,
name: "Apple Watch 8",
price: 3000,
},
},
],
};
},
computed: {
chkAll: {
set(v) {
this.carts.forEach((item) => (item.chk = v));
},
// get的时候一定要记得加return
get() {
return this.carts.every((item) => item.chk);
},
},
sumPrice() {
return this.carts
.filter((item) => item.chk)
.reduce((pre, cur) => pre + cur.amount * cur.product.price, 0);
},
},