这篇文章主要介绍了优雅的将ElementUI表格变身成树形表格的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
由于ElementUI目前还未开发树形表格组件,也参阅了网络上部分基于ElementUI表格封装的开源树形组件,如果想进行二次开发的话都不太理想,所以就萌生了自行开发树形表格。
本示例提供开发思路,移除了多余的样式,比较适合新手入门学习,如果应用于实际项目还请自行封装。
目前还仅仅实现了视觉的树结构的层级效果和控制结构的显示隐藏,后续还会进行不断的完善和优化,有必要的话会对组件进行二次封装,有点在重复造论的感觉哈。
效果图
完整代码
页面(tree-table.vue)
<div> TreeTable <span class="collapse"> </span><span>{{ scope.row.id }}</span></div> .collapse { display: inline-block; width: 8px; cursor: pointer; margin-right: 8px; } .collapse<span style="color:transparent">本文来源gaodai#ma#com搞*!代#%^码$网!</span>--open:before { content: '+'; } .collapse--close:before { content: '-'; }
工具方法
考虑数组转树和遍历树都是在实际项目中都是非常常用的,所以这边对这两个方法进行了封装。
数组转树结构(./utils/array.ts)
export function arrayToTree(list: object[], props = {id: 'id', pid: 'pid', children: 'children'}) { let tree: object[] = []; let map: any = {}; let listLength = list.length; for (let i = 0; i <listLength; i++) { let node: any = list[i]; let nodeId: any = node[props.id]; map[nodeId] = node; } for (let i = 0; i <listLength; i++) { let node: any = list[i]; let nodePid: any = node[props.pid]; let parentNode: any = map[nodePid]; if (parentNode) { parentNode[props.children] = parentNode[props.children] || []; parentNode[props.children].push(node) } else { tree.push(node) } } return tree }
遍历树结构(./utils/tree.ts)
结合实际项目应用,我们采用了先序遍历法对树进行遍历,为了方便在业务代码里的应用,在遍历过程中会对每个节点挂载节点访问路径 _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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网。
以上就是优雅的将ElementUI表格变身成树形表格的方法步骤的详细内容,更多请关注gaodaima搞代码网其它相关文章!