发请求拿到的数据是一个数组
res:[
{TENANT_ID_: "001",company_code: "00",company_name: "大坝1",id: "1",pid: "987"},
{TENANT_ID_: "0010",company_code: "010",company_name: "大坝1-1",id: "1-1",pid: "987-1"},
{TENANT_ID_: "00101",company_code: "010",company_name: "大坝1-1.1",id: "1-1.1",pid: "987-1.1"},
{TENANT_ID_: "002",company_code: "00",company_name: "大坝2",id: "2",pid: "999"},
{TENANT_ID_: "0020",company_code: "010",company_name: "大坝2-1",id: "2-1",pid: "999-1"},
{TENANT_ID_: "00201",company_code: "010",company_name: "大坝2-1.1",id: "2-1.1",pid: "999-1.1"}
]
写的html 以及定义数据
<ht-tree
:tree-data="data"
:props="defaultProps"
leaf-only = "true"
include-half-checked = "true"
@refresh="handleRefresh"
@node-click="handleNodeClick"
>
</ht-tree>
export default {
data() {
return {
data:[],
defaultProps: {
children: 'children',
label: 'company_name'
},
}
}
}
想要element el-tree树的效果一样,可以附上完整代码
简单写了下,从案例上可以满足,给你个思路
let res = [
{ TENANT_ID_: "001", company_code: "00", company_name: "大坝1", id: "1", pid: "987" },
{ TENANT_ID_: "0010", company_code: "010", company_name: "大坝1-1", id: "1-1", pid: "987-1" },
{ TENANT_ID_: "00101", company_code: "010", company_name: "大坝1-1.1", id: "1-1.1", pid: "987-1.1" },
{ TENANT_ID_: "002", company_code: "00", company_name: "大坝2", id: "2", pid: "999" },
{ TENANT_ID_: "0020", company_code: "010", company_name: "大坝2-1", id: "2-1", pid: "999-1" },
{ TENANT_ID_: "00201", company_code: "010", company_name: "大坝2-1.1", id: "2-1.1", pid: "999-1.1" }
]
let arr = []
res.map(item => {
item.children = []
if (item.TENANT_ID_.length === 3) {
arr.push(item)
} else if (item.TENANT_ID_.length === 4) {
let index = arr.findIndex(findChild => findChild.TENANT_ID_ === item.TENANT_ID_.substring(0, 3))
arr[index].children.push(item)
} else if (item.TENANT_ID_.length === 5) {
let firstIndex = arr.findIndex(findChild => findChild.TENANT_ID_ === item.TENANT_ID_.substring(0, 3))
let secondIndex = arr[firstIndex].children.findIndex(findChild => findChild.TENANT_ID_ === item.TENANT_ID_.substring(0, 4))
arr[firstIndex].children[secondIndex].children.push(item)
}
})
console.log('arr', arr)
function arrayToTree(items) {
const result = [];
const itemMap = {}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}