由於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