el-table复选框父子关联(联级)选择
在Element UI中,el-table
组件支持复选框,并且可以通过设置row-key
和expand-row-keys
属性来实现父子关系的复选框联动。以下是一个简单的实现例子:
<template>
<el-table
:data="tableData"
row-key="id"
:expand-row-keys="expandRowKeys"
@selection-change="handleSelectionChange"
@expand-change="handleExpandChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column type="expand">
<template slot-scope="props">
<el-table
:data="props.row.children"
row-key="id"
@selection-change="handleChildSelectionChange(props.row)"
>
<el-table-column type="selection" width="55"></el-table-column>
<!-- 其他列 -->
</el-table>
</template>
</el-table-column>
<!-- 其他列 -->
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
// 父行数据,包含子行数据
],
expandRowKeys: [], // 控制展开行的数组
selection: [], // 控制所有选中项的数组
};
},
methods: {
handleSelectionChange(selection) {
this.selection = selection;
// 更新子行的选中状态
this.tableData.forEach(row => {
if (this.selection.includes(row)) {
this.expandRowKeys.push(row.id);
row.children.forEach(child => {
this.$refs[row.id][0].toggleRowSelection(child, true);
});
} else {
this.expandRowKeys = this.expandRowKeys.filter(key => key !== row.id);
row.children.forEach(child => {
this.$refs[row.id][0].toggleRowSelection(child, false);
});
}
});
},
handleExpandChange(row, expandedRows) {
if (expandedRows.length) {
this.handleSelectionChange(this.selection.concat(row));
} else {
this.handleSelectionChange(this.selection.filter(item => item !== row));
}
},
handleChildSelectionChange(parentRow) {
const isParentSelected = this.selection.includes(parentRow);
const selectedChildren = this.$refs[parentRow.id][0].selection;
const allChildrenSelected = parentRow.children.every(child => selectedChildren.includes(child));
if (allChildrenSelected && !isParentSelected) {
this.handleSelectionChange(this.selection.concat(parentRow));
} else if (!allChildrenSelected && isParentSelected) {
this.handleSelectionChange(this.selection.filter(item => item !== parentRow));
评论已关闭