我们在vue项目开发过程中,免不了要使用树形控件,基本上Ui组件库都需要的是递归数组,比如[{id:1,name:'xxx',chidren:[{id;11,name:'xxx',children:[{d;111,name:'xxx'}]}]},{id:2,name:'xxx',chidren:[]}]
,但是后端传给我们的数据可能不是这种处理好的数组,比如传的是这样的格式:
[{id:1,pid:0,name:'xxx'},
{id:11,pid:1,name:'xxx'},
{id:111,pid:11,name:'xxx'},
{id:112,pid:11,name:'xxx'},
{id:2,pid:0,name:'xxx'},
{id:12,pid:1,name:'xxx'},]
那么我们就要去处理这个数据再赋值给树状控件数组,这里采用了若依的方法处理数据
//第一个参数是后端传的数据,第二个参数是自身的标识字段,第三个参数是绑定的父数据标识字段,第四个数据是递归数组的字段(第一个参数是必传,第二个参数不传默认字段就是'id',第三个参数不传默认字段就是'parentId',,第三个参数不传默认字段就是'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;
}
举个列子,我们可以this.treeList=this.handleTree(res.data.list,'id','pid','children')
赋值给树状控件数组