优雅的将ElementUI表格变身成树形表格的方法步骤(2)

结合实际项目应用,我们采用了先序遍历法对树进行遍历,为了方便在业务代码里的应用,在遍历过程中会对每个节点挂载节点访问路径 _idPath 属性和节点深度 _depth 属性。

export function ergodicTree(tree: object[], callback: any = () => {}, props = {id: 'id', pid: 'pid', children: 'children'}) { function _ergodicTree(tree: object[], parentIdPath?: any[], depth: number = 0) { const treeLength = tree.length; for (let i = 0; i < treeLength; i++) { let node: any = tree[i]; const _idPath: any[] = parentIdPath ? [...parentIdPath, node[props.id]] : [node[props.id]]; const _depth: number = depth + 1; node._idPath = _idPath; node._depth = _depth; callback(node); if (node[props.children] && node[props.children] instanceof Array) { _ergodicTree(node[props.children], _idPath, _depth) } } } _ergodicTree(tree); return tree; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/59e29f8c79c1ead03d09f693043694dc.html