el-table:
<el-table
ref="multipleTable"
:data="tableData[0].children"
style="width: 100%; margin-bottom: 20px"
row-key="id"
v-loading="loading"
:select-on-indeterminate="true"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
@select="selectTr"
@select-all="selectAll"
@selection-change="handleSelectionChange"
>
先给拉取的数据添加一个 isSelect 属性
//递归添加属性
deepAdd(data) {
if (!data) return;
data.forEach((item) => {
item.isSelect = false
if (item.children instanceof Array) {
this.deepAdd(item.children);
}
});
return data;
},
方法如下:
我的树形结构数据外有个主类 所以我传递的参数是 this.tableDate[0].children
//我的树形结构是这样的
tableData: [
{
id: 0,
level: 0,
parentId: 0,
label: "主类",
children: [
// 。。。。。。。。。。
],
},
],
//选中table赋值 如果需要获取选中的值 下方输出的就是
handleSelectionChange(selection) {
console.log(this.getChecked(this.tableData[0].children));
},
// 全选/取消选操作
selectAll() {
this.isAllSelect = !this.isAllSelect;
this.changeChildren(this.tableData[0].children,this.isAllSelect)
},
//选中某一行
selectTr(select,row){
row.isSelect = !row.isSelect
if(row.children instanceof Array){
this.changeChildren(row.children,row.isSelect)
}
for (let i = 0; i < 6; i++) {
this.changeParent(this.tableData[0].children)
}
},
//选中所有children
changeChildren(table,isAllSelect){
table.forEach(item => {
item.isSelect = isAllSelect
this.$refs.multipleTable.toggleRowSelection(item,isAllSelect);
if(item.children instanceof Array){
this.changeChildren(item.children,isAllSelect)
}
})
},
//选中所有父元素
changeParent(table){
table.forEach(item => {
if(item.children instanceof Array){
this.$refs.multipleTable.toggleRowSelection(item,item.children.every(i => i.isSelect));
item.isSelect = item.children.every(i => i.isSelect)
this.changeParent(item.children)
}
})
},
//递归找选中的项
getChecked(table) {
let list = {ids:[],labels:[]};
let fn = (table) => {
for (let i = 0; i < table.length; i++) {
if (table[i].isSelect) {
list.ids.push(table[i].id)
list.labels.push(table[i].label)
}
if (table[i].children && table[i].children.length > 0) {
fn(table[i].children);
}
}
};
fn(table);
return list;
},
//选中某一行
selectTr(select,row){
row.isSelect = !row.isSelect
if(row.children instanceof Array){
this.changeChildren(row.children,row.isSelect)
}
//这个for循环是 层级有几层就循环多少次就ok
for (let i = 0; i < 6; i++) {
this.changeParent(this.tableData[0].children)
}
},