效果如下:
<div id="options">
<div class="title">
<el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="checkAll">
全选
</el-checkbox>
</div>
<div class="buttons" v-for="(item, index) in allOptions" :id="item" :key="index" @click="checkSingle">
{{item}}
<div class="select-border" v-show="checkedOptions.indexOf(item) != -1">
<span class="select-border-text">✓</span>
</div>
</div>
</div>
checkAll (isAll) {
this.isCheckAll = isAll
this.isIndeterminate = false
let buttons = document.getElementById('options').children
for (let i = 1; i < buttons.length; i++) {
let displayStatus = buttons[i].children[0].style.display
if (isAll) {
// 选中所有
if (displayStatus == "block") {
continue
} else {
buttons[i].children[0].style.display = 'block'
}
} else {
// 全部不选
if (displayStatus == "none") {
continue
} else {
buttons[i].children[0].style.display = 'none'
}
}
}
if (isAll) {
this.selectLayers = this.filterLayers
} else {
this.selectLayers = []
}
},
// 选中单个选项
checkSingle (event) {
let target = event.currentTarget
let id = target.id
// 获取当前div元素的选中状态
let element = target.children[0]
let showStatus = element.style.display
// 控制图层的显隐
if (showStatus == "none") {
element.style.display = 'block'
this.checkedOptions.push(id)
} else {
element.style.display = 'none'
this.checkedOptions = this.checkedOptions.filter(ele => ele != id)
}
// 判断是否全选或者全不选
let children = target.parentElement.children
let blockCount = 0, noneCount = 0;
let tempSelectLayer = []
debugger
for (let i = 1; i < children.length; i++) {
let displayStatus = children[i].children[0].style.display
if (displayStatus == "none") {
noneCount++
} else {
blockCount++
}
}
// 更新“全选”checkbox的状态
if (blockCount > 0 && noneCount > 0) {
// 部分选中,部分不选
this.isCheckAll = false
this.isIndeterminate = true
} else if (blockCount > 0 && noneCount == 0) {
// 全部选中
this.isCheckAll = true
this.isIndeterminate = false
} else if (blockCount == 0 && noneCount > 0) {
// 全部不选
this.isCheckAll = false
this.isIndeterminate = false
} else {
return
}
}
完整代码