在开发后台管理系统的时候,有时需要实现表格某一列可折叠的情况,如下所示:
但是后端返回给我们的数据却又是这样的:
此时,我们则需要通过手写函数,将后端返回给我们的data数据转化为可用的树形结构,代码如下所示:
listToTreeMulti(list, root = 0, pk = 'id', pid = 'parentId', child = 'children', other = null) {
const tree = []
if (list) {
list.forEach(item => {
if (item[pid] === root) {
if (other !== null) {
item = objectMerge(item, other)
}
const children = listToTreeMulti(list, item[pk], pk, pid, child, other)
if (children.length) {
item[child] = children
}
tree.push(item)
}
})
}
return tree
}
//然后在computed中调用函数,得到所需的树形结构数组(getData)
computed:{
getData(){
//this.data即为后端给我们返回的数组
const t = this.listToTreeMulti(this.data);
return t;
}
}
//最后在el-table中使用即可
<el-table
row-key="id"
:data="getData"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
>
</el-table>