由于iview的tree组件不可以知足咱们现有项目的要求,因此打算从新封装tree组件,就看了iview中对tree组件data处理的方法,感受很不错,分享下,哈哈。node
compileFlatState () { // so we have always a relation parent/children of each node
let keyCounter = 0;
let childrenKey = this.childrenKey; // childrenKey是组件传递进来的子数组的字段名
const flatTree = [];
// flattenChildren方法回将原始数据的每一项
function flattenChildren(node, parent) {
node.nodeKey = keyCounter++;
flatTree[node.nodeKey] = { node: node, nodeKey: node.nodeKey };
if (typeof parent != 'undefined') {
flatTree[node.nodeKey].parent = parent.nodeKey;
flatTree[parent.nodeKey][childrenKey].push(node.nodeKey);
}
if (node[childrenKey]) {
flatTree[node.nodeKey][childrenKey] = [];// 是上面flatTree[parent.nodeKey][childrenKey]的初始化
node[childrenKey].forEach(child => flattenChildren(child, node));
}
}
this.stateTree.forEach(rootNode => { // stateTree是原始的data数据
flattenChildren(rootNode);
});
return flatTree; // flatTree是对data处理完后的结果
}
复制代码
flattenChildren方法将原始数据的每一项变为数组
{
node: '原始数据',
nodeKey: '是flatTree数组的第几项',
parent: '若是有父级,父级的nodeKey',
[childrenKey]: '数组,子级有几项'
}
复制代码
固然还有其余一些控制勾选、展开状态的值。iview
data = [{
title: 'a1',
children: [{
title: 'b1',
children: [{
title: 'c1'
}, {
title: 'c2'
}]
}, {
title: 'b2'
}]
}]
复制代码
转变为this
flatTree = [{
"node": {
"title": "a1",
"children": [{
"title": "b1",
"children": [{
"title": "c1",
"nodeKey": 2
}, {
"title": "c2",
"nodeKey": 3
}],
"nodeKey": 1
}, {
"title": "b2",
"nodeKey": 4
}],
"nodeKey": 0
},
"nodeKey": 0,
"children": [
1,
4
]}, {
"node": {
"title": "b1",
"children": [ {
"title": "c1",
"nodeKey": 2
}, {
"title": "c2",
"nodeKey": 3
}],
"nodeKey": 1
},
"nodeKey": 1,
"parent": 0,
"children": [
2,
3
]}, {
"node": {
"title": "c1",
"nodeKey": 2
},
"nodeKey": 2,
"parent": 1
}, {
"node": {
"title": "c2",
"nodeKey": 3
},
"nodeKey": 3,
"parent": 1
}, {
"node": {
"title": "b2",
"nodeKey": 4
},
"nodeKey": 4,
"parent": 0
}]
复制代码
经过nodeKey能够快速定位到它在flatTree中的位子,能够经过parent快速定位到父级在flatTree中的位子,能够经过[childrenKey]快速定位到它全部子级在flatTree中得分位子,而后经过node获取对应的数据。初始化的一次深度遍历解决全部后面的问题。spa