el-tree 树形结构数据转换
后端返回的数据格式
转成el-tree接收的格式
// 树形结构数据转换 每个元素的 children 属性对应的 value 通过 pid 去找到,然后递归执行下去 arrToTree(arr, upperDeptId = '0') { const res = [] arr.forEach(item => { if (item.upperDeptId == upperDeptId) { const children = this.arrToTree(arr.filter(v => v.upperDeptId !== upperDeptId), item.id) if (children.length) { res.push({ ...item, children }) } else { res.push({ ...item }) } } }) return res },
getDeptList({ pageIndex: 1, pageSize: 1000, upperDeptId: '' }).then(res => {
const list = res.data.list
this.departmentList = this.arrToTree(list, '0')
// 默认高亮第一个节点
this.$nextTick(() => {
this.$refs.deptTree.setCurrentKey(list[0].id)
})
})
转换后的数据格式
方式二
/** * 构造树型结构数据 * @param {*} data 数据源 * @param {*} id id字段 默认 'id' * @param {*} parentId 父节点字段 默认 'parentId' * @param {*} children 孩子节点字段 默认 'children' */ export function handleTree(data, id, parentId, children) { let config = { id: id || 'id', parentId: parentId || 'parentId', childrenList: children || 'children' }; var childrenListMap = {}; var nodeIds = {}; var tree = []; for (let d of data) { let parentId = d[config.parentId]; if (childrenListMap[parentId] == null) { childrenListMap[parentId] = []; } nodeIds[d[config.id]] = d; childrenListMap[parentId].push(d); } for (let d of data) { let parentId = d[config.parentId]; if (nodeIds[parentId] == null) { tree.push(d); } } for (let t of tree) { adaptToChildrenList(t); } function adaptToChildrenList(o) { if (childrenListMap[o[config.id]] !== null) { o[config.childrenList] = childrenListMap[o[config.id]]; } if (o[config.childrenList]) { for (let c of o[config.childrenList]) { adaptToChildrenList(c); } } } return tree; }