- 点击全选按钮,切换所有商品选中、未选中状态
- 监测每个商品的按钮状态。即:当所有商品选中时,全选按钮自动选中、有一商品是未选中状态时,全选按钮也为未选中状态。
- 每个商品数据中包含各自的按钮状态
//HTML部分
//每个商品的按钮部分
<view @click="clickChecked(index)">
<image v-if="item.checked" src="../../static/indent/ic-checbox.png"></image>
<image v-else src="../../static/store/ic-checbox.png"></image>
</view>
//index:v-for遍历数据时的index
//item.checked:值是一个布尔值
//全选按钮部分
<view @click="clickCheckAll">
<image v-if="checkAllState" src="../../static/indent/ic-checbox.png"></image>
<image v-else src="../../static/indent/ic-checkbox-normal.png"></image>
<text>全选</text>
</view>
//checkAllState 的返回值是一个布尔值
//JS部分
data() {
return {
indentList: [ //订单列表
{ name: '布罗利超赛4手办',
checked: true,
num: '1'
}
]}},
//全选按钮
clickCheckAll() {
if (this.checkAllState) {
this.indentList.forEach(item => item.checked = false)
} else {
this.indentList.forEach(item => item.checked = true)
}
},
//商品按钮
clickChecked(index) {
this.indentList[index].checked = !this.indentList[index].checked
},
computed: { //在computed中定义的属性可以监视订单列表中每个商品选择框的状态
checkAllState() {
return this.indentList.every(item => item.checked == true)
}
}
- 每个按钮通过 v-if 绑定一个布尔值来切换状态
- 全选按钮中 v-if 绑定的值在 computed 中定义,可以监测每一项中 checked 的变化,当每一项的 checked=true 时,代表每个商品为选中状态,every() 会返回一个布尔值true,此时全选按钮的状态为选中状态。 --- 完成功能2
- 商品按钮通过 index 来修改对应的商品选中状态
- 点击全选按钮时,判断此时 checkAllState 的值,为 true 时,代表此时是全选状态,点击全选按钮是要将所有商品各自的按钮状态切换为未选中状态,于是遍历每个商品将checked改为false,反之为false时,将所有商品的checked改为true。 --- 完成功能1