根据业务需求 需要实现一个全选反选 样式如下图
用select 加Checkbox 多选框实现样式
<template>
<el-select v-model="dataForm.checked" multiple >
<el-checkbox class="checkS" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
<el-option v-for="item in cities" :key="item.id" :label="item.label" :value="item.id">
<el-checkbox :value="dataForm.checked.includes(item.id)" :label="item.label" :key="item.id" @change="(val)=>secleChange(val,item)">{{ item.label }}</el-checkbox>
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '选项A' },
{ id: 2, name: '选项B' },
{ id: 3, name: '选项C' },
// ...更多选项
],
checkedList: [], // 已选项
checkAll: false, // 全选框状态
isIndeterminate: false, // 不确定状态
};
},
watch: {
dataForm:{
handler(newVal, oldVal) {
console.log('Message changed from', oldVal, 'to', newVal);
if(newVal.checked.length > 0 && newVal.checked.length!= this.cities.length){
this.isIndeterminate = true
}else if(newVal.checked.length > 0 && newVal.checked.length == this.cities.lengt){
this.checkAll = true
}else if(!newVal.checked.length){
this.checkAll = false
this.isIndeterminate = false
}
},
deep: true, // 深度监听msg对象内部属性的变化
immediate: true // 组件初始化时立即执行handler函数
}
},
methods: {
// 全选
handleCheckAllChange(val) {
if(val){
// 选中
this.dataForm.checked = this.cities.map(i =>{ return i.id})
}else{
// 未选中
this.dataForm.checked = []
}
},
secleChange(val,row){
// 选择框单个多选
console.log(val,row)
if(val){
// 取消
let newarr = this.dataForm.checked.filter((k,index) => {
if(val){
return k != row.id
}
})
return this.$set(this.dataForm,'checked',newarr)
}else{
// 新增
const newArry = [...this.dataForm.checked,row.id]
return this.$set(this.dataForm,'checked',newArry)
}
},
// 默认全选(在mounted调用)
initSelect(){
if(this.secondaryList){
this.dataForm.customerIdList = this.secondaryList.map(i =>{ return i.id})
this.checkAll = true
}
},
},
};
</script>
<style lang="scss" scoped>
.checkS{
padding:0 20px;
}
/deep/.el-select-dropdown.is-multiple,.el-select-dropdown__item.selected::after {
display:none !important;
}
</style>