el-tree根据parentId生成树

组件: Element(地址:http://element.eleme.io/#/zh-CN/component/tree):Tree树形控件

<el-tree
:data="dataRole"
show-checkbox
ref="tree"
node-key="id"
:check-strictly="true"
default-expand-all
:default-checked-keys="dataActive"
@check-change="getCheckedKeys"
:props="defaultProps">
</el-tree>

将获取的数据转换成组件所需要的格式:

let menuData = []
res.data.data.map(item => {
    menuData.push({
        "id": item.id,
        "parentId": item.parentId,
        "label": item.name,
        "children": []
    })
})

然后根据parentId生成树:

function setTree(data, Pid) {
    let result = []
    let child
    for (let i = 0; i < data.length; i++) {
        if (data[i].parentId == Pid) {
            child = setTree(data, data[i].id)
            if (child.length > 0) {
                data[i].children = child
            }
            result.push(data[i])
        }
    }
    return result
}
this.dataRole = setTree(menuData, 0) //rootid为0

发表评论

电子邮件地址不会被公开。 必填项已用*标注