elmentui中table组件中父子结构勾选的相关问题
业务场景
在使用 element-ui 中的 table 组件并以父子结构展示数据时,有勾选的需求,需要在勾选父数据时,将子数据一起勾选,取消勾选父数据也会将子数据取消勾选;但是在 element-ui 中并没有提供现成的方法;
实现
思路:使用 table 组件中的 select 方法(每次勾选或者取消勾选时都会触发该方法),并以 isCheck 字段存储数据的勾选状态,便于后续操作中有回显勾选数据的操作;
例子(使用的是 vue):
// vue
<el-table
ref="districtTable"
:data="tableData"
row-key="id"
@select="handleSelectionChange"
:tree-props="{children: 'children', hasChildren: 'hasChildren'}">
<el-table-column
type="selection"
width="55">
</el-table-column>
...
</el-table>
<button @click="getTargetData">获取表格数据</button>
handleSelectionChange(select, row) {
let dataArr = [row]; // 将数据改造为数组,便于封装后的方法 changeRow 进行操作
// 如果当前的数据的 isCheck 没有被勾选过,则该字段的值应该为 false/undefined
// 给该数据定义后续操作是需要勾选还是取消勾选
if (row.isCheck) {
row.isCheck = false
} else {
row.isCheck = true
}
this.changeRow(dataArr, row.isCheck)
},
// data - 需要进行操作的数据
// type - 要进行的操作类型(true-需要被勾选,false-需要取消勾选)
changeRow(data, type) {
Array.from(data).forEach((row) => {
row.isCheck = type;
this.$refs.districtTable.toggleRowSelection(row, type); // element-ui 自带的方法,用于改变传入参数 row 的勾选状态
if (row.children && row.children.length > 0) { // 判断当前数据是否有子数据,如果有则进行递归操作
this.changeRow(row.children, type);
}
});
},
getTargetData() { // 获取 table 数据
console.log(this.$refs.districtTable.selection)
},