# 转换后台传来的tree格式
后台返回的格式是parentId+id,children:[],可以忽略,需要前端手动转化成children是嵌套的elementui的标准格式
- 非ts和eslint模式,如果开启eslint,还需修改一些配置如== 等
/**
* 构造树型结构数据
* @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;
}
在vue的element项目中使用main.js中配置
import { handleTree } from "@/utils/xxxx";
// 全局方法挂载
Vue.prototype.handleTree = handleTree
//调用handletree,把格式改为children嵌套的符合element的格式;
fetch('http://localhost:3000/9.json').then(res=>res.json()).then(response=>{
this.deptList = this.handleTree(response.data, "deptId");
this.loading = false;
})