平铺数组转为树结构
function buildTree(array, id = 'id', pid = 'pid') {
const map = {}
const roots = []
// 创建索引映射关系
for (const item of array) {
map[item[id]] = { ...item, children: [] }
}
// 构建树结构
for (const item of array) {
const parent = map[item[pid]]
if (parent) {
parent.children.push(map[item[id]])
} else {
roots.push(map[item[id]])
}
}
return roots
}
<template>
<div class="test-tree" style="width: 100%; height:500px;background: #fff">
<el-tree :props="props" :load="loadNode" lazy show-checkbox> </el-tree>
</div>
</template>
<script>
import request from "@/router/axios";
export default {
data() {
return {
props: {
label: "text",
value: "id",
children: "children",
isLeaf: "isLeaf"
}
};
},
methods: {
buildTree(array, id = "id", pid = "pid") {
const map = {};
const roots = [];
for (const item of array) {
map[item[id]] = {
...item,
children: [],
isLeaf: item.isLeaf === "0" ? false : true
};
}
for (const item of array) {
const parent = map[item[pid]];
if (parent) {
parent.children.push(map[item[id]]);
} else {
roots.push(map[item[id]]);
}
}
return roots;
},
async loadNode(node, resolve) {
console.log(node, "我是一颗树");
if (node.level === 0) {
const { data } = await request({
url: "/tree/lazyTree",
method: "post",
data: {
root: "",
bakTime: "",
cancelFlag: "00901"
}
});
if (data.code === "0") {
const tree = this.buildTree(data.data);
console.log(tree);
return resolve(tree);
}
}
if (node.level === 1) {
return resolve(node.data.children);
}
if (node.level > 1) {
const { data } = await request({
url: "/tree/lazyTree",
method: "post",
data: {
root: "",
bakTime: "",
cancelFlag: "00901",
id: node.data.id
}
});
if (data.code === "0") {
const tree = this.buildTree(data.data);
return resolve(tree);
}
}
}
}
};
</script>
<style></style>