请看代码:
<div id="app">
<ul>
<!-- 单个复选框的情形 -->
<input type="checkbox" v-model="isCheckAll" @change="handler" />
全选/全不选
<button @click="antiSelect">反选</button>
<li
v-for="(item,index) in cartData"
:key="item.id"
style="list-style: none"
>
<!-- 该处为多个复选框的情形 -->
<input
type="checkbox"
:value="item.id"
v-model="checkedArr"
@change="isCheckedAll"
/>
商品id:{{item.id}}  
商品名称:{{item.name}}  
商品单价:{{item.price}}   商品数量:<button
@click="decr(index,item)"
>
-</button
>{{item.num}}<button @click="incr(index,item)">+</button
>   商品小计:{{item.price * item.num}}
</li>
</ul>
</div>
var cartData = [
{
id: 1,
name: "小米",
price: 100,
num: 1,
},
{
id: 2,
name: "华为",
price: 200,
num: 1,
},
{
id: 3,
name: "联想",
price: 300,
num: 1,
},
];
new Vue({
el: "#app",
data: {
cartData,
// 是选全选
isCheckAll: false,
// 选中的元素集合
checkedArr: [],
},
methods: {
decr: function (index, item) {
if (item.num === 1) {
// 短路运算
// confirm("这么好的商品你确认就不买了吗?") &&
// this.cartData.splice(index, 1)
if (confirm("这么好的商品你确认就不买了吗?")) {
this.cartData.splice(index, 1);
//选中返回0 不选中返回-1
let key = this.checkedArr.indexOf(item.id);
console.log(key)
//如果不是-1证明有
if (key > -1) {
// 删除选中记录
this.checkedArr.splice(key, 1);
}
}
return false;
}
item.num--;
},
incr: function (index, item) {
item.num++;
},
// 全选/全不选
handler: function () {
this.checkedArr = [];
if (this.isCheckAll) {
// 循环,将挨个的商品的id丢到checkedArr里面去
this.cartData.forEach((el) => {
this.checkedArr.push(el.id);
});
}
},
// 通过商品的复选框改变“全选/全不选”复选框的状态
isCheckedAll: function () {
this.isCheckAll =
this.checkedArr.length === this.cartData.length;
// this.isCheckAll = this.checkedArr.length === this.cartData.length ? true : false
// if (this.checkedArr.length === this.cartData.length) {
// this.isCheckAll = true;
// } else {
// this.isCheckAll = false;
// }
},
// 反选
antiSelect: function () {
// 循环整个商品列表
let tmp = [];
this.cartData.forEach((el) => {
// arr.includes(el)
// 表示在arr中判断是否包含el,如果包含则返回true,否则返回false
if (!this.checkedArr.includes(el.id)) {
// 说明么有,则要
tmp.push(el.id);
}
});
// this.cartData.forEach((el) => {
// if (this.checkedArr.indexOf(el.id) === -1) {
// // 说明么有,则要
// tmp.push(el.id);
// }
// });
this.checkedArr = tmp;
},
},
});