使用watch来监听选中数组checkList里面的数量,到底是显示isIndeterminate(-),还是checkAll(√)
获取数据
<template>
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="changeAll">全选</el-checkbox>
<div style="margin: 15px 0;"></div>
<el-checkbox-group v-model="checkList">
<el-checkbox v-for="item in btnList" :label="item._id" :key="item._id">{{item.title}}</el-checkbox>
</el-checkbox-group>
</template>
复制代码
data() {
return {
btnList:[], // 所有列表
checkList:[], // 选中的数组,里面只能是[id,id,id]
checkAll:undefined,
isIndeterminate: undefined,
}
}
created() {
this.getBtnsList()
},
watch: {
checkList(){
let checkedCount = this.checkList.length //获取选中列表的数量
//如果等于所有列表的length,就为true,就使用(√)
this.checkAll = checkedCount === this.btnList.length
//如果选中列表的数量大于0,小于列表的length,就使用(-)
this.isIndeterminate = checkedCount > 0 && checkedCount < this.btnList.length;
}
},
methods: {
// 单击全选checkbox
changeAll(val){
//这个必须是[1,2,3] ,不能为[{},{}],不然不能渲染到页面中去
this.checkList = val ? this.btnList.map(v => v.id) :[]
},
// 获取数据
getBtnsList(){
this.listLoading = true
btnFind().then(res=>{
this.btnList = res
this.listLoading = false
})
},
}
复制代码