后端返回的數據格式

轉成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;
}
