iview中tree组件多级数组的处理

1,702 阅读1分钟

写在前面

因为iview的tree组件不能够满足我们现有项目的要求,所以打算重新封装tree组件,就看了iview中对tree组件data处理的方法,感觉很不错,分享下,哈哈。

代码

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]: '数组,子级有几项'
}

当然还有其他一些控制勾选、展开状态的值。

最终数据格式

data = [{
    title: 'a1',
    children: [{
      title: 'b1',
      children: [{
        title: 'c1'
      }, {
        title: 'c2'
      }]
    }, {
      title: 'b2'
    }]
}]

转变为

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获取对应的数据。初始化的一次深度遍历解决所有后面的问题。