最终实现结果
由于element-ui没有原始api来实现这种全选,半选,所以自己写了一点
@select="selectFun"
@selectAll="selectAllFun"
element-ui的原始方法
表格数据初始化
this.tableData =====> 表格数据
this.tableData.map(item => {
this.$set(item, 'isSelect', false); //默认父级不选中
item.children.map(childItem => {
this.$set(childItem, 'isSelect', false); //默认子级不选中
}
}
设置当前点击的复选框应该呈现出的状态的具体方法
setRowClickStatus(row) {
//点击父级复选框时,当前的状态可能为半选,所以当前行状态设为false并选中,即可实现子级点全选效果
if(row.isSelect === '') {
row.isSelect = false;
this.$refs.table.$refs.refTable.toggleRowSelection(row, true);//element自带事件
}
row.isSelect = !row.isSelect;
//判断点击的是子级复选框还是父级复选框,如果是父级就控制子级的状态
if(row.children) {
//含有children字段,操作的是父级
row.children.map(item => {
item.isSelect = row.isSelect;
this.$refs.table.$refs.refTable.toggleRowSelection(item, item.isSelect);
})
} else {
//操作的是子级,控制父级的选中,不选中,半选
let parentId = row.parentId; //数据中的父级id字段
this.tableData.map(item => {
let isAllSelect = [];
if(item.catelogid == parentId){ //自身id匹配到点击的id相同
item.children.map(childItem => {
isAllSelect.push(childItem.isSelect);
})
if(isAllSelect.every(slectItem => true == slectItem )){
item.isSelect = true;
this.$refs.table.$refs.refTable.toggleRowSelection(item, true);
} else if (isAllSelect.every(selectItem => false == selectItem)){
item.isSelect = false;
this.$refs.table.$refs.refTable.toggleRowSelection(item, false);
} else{
item.isSelect = ''; //半选状态
}
}
})
}
}
复选框点击事件
selectFun(selection, row) {
this.setRowClickStatus(row);
}
点击表头全选事件
1.检测表格数据是否全选
checkIsAllSelect() {
let oneLevelIsSelect = [];
this.tableData.map(item => {
oneLevelIsSelect.push(item.isSelect);
})
let isAllSelect = oneLevelIsSelect.every(levelItem => true == levelItem );
retrun isAllSelect;
}
2.全选事件
selectAllFun(selection) {
let isAllSelect = this.checkIsAllSelect();
this.tableData.map(item => {
item.isSelect = isAllSelect;
this.$refs.table.$refs.refTable.toggleRowSelection(item, !isAllSelect);
this.selectFun(selection, item);
})
}
控制自定义的父级半选样式
1.表格父级半选样式:headerCellClassName="headerRowClassName"
headerRowClassName({ row }){
let oneLevelIsSelect = [];
this.tableData.map(item => {
oneLevelIsSelect.push(item.isSelect);
})
if(oneLevelIsSelect.includes('')) {
return 'indeterminate-custom';
}
return "";
}
2.css样式
.indeterminate-custom {
.el-checkbox__input {
.el-checkbox__inner {
background-color: #409eff !important;
border-color: #409eff !important;
color: #fff !important;
&::before {
content: '';
position: absolute;
display: block;
background-color: #FFF;
height: 2px;
transform: scale(.5);
left: 0;
right: 0;
top: 5px;
}
&::after {
content: none;
}
}
}
}