vue实现表格树
Vue 实现表格树的方法
使用递归组件实现表格树
递归组件是处理树形结构的常用方法。通过组件自身调用自身,可以逐层渲染树形结构。
<template>
<table>
<thead>
<tr>
<th>名称</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tree-node v-for="node in treeData" :node="node" :key="node.id"></tree-node>
</tbody>
</table>
</template>
<script>
import TreeNode from './TreeNode.vue'
export default {
components: { TreeNode },
data() {
return {
treeData: [
{
id: 1,
name: '父节点1',
value: '100',
children: [
{
id: 2,
name: '子节点1',
value: '50'
}
]
}
]
}
}
}
</script>
<!-- TreeNode.vue -->
<template>
<tr>
<td>{{ node.name }}</td>
<td>{{ node.value }}</td>
</tr>
<template v-if="node.children">
<tree-node
v-for="child in node.children"
:node="child"
:key="child.id"
></tree-node>
</template>
</template>
<script>
export default {
name: 'TreeNode',
props: {
node: Object
}
}
</script>
使用第三方库实现表格树
对于更复杂的需求,可以考虑使用成熟的第三方库如element-ui的el-table配合树形数据。
<template>
<el-table
:data="treeData"
row-key="id"
default-expand-all
:tree-props="{children: 'children', hasChildren: 'hasChildren'}">
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="value" label="值"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
treeData: [
{
id: 1,
name: '父节点1',
value: '100',
children: [
{
id: 2,
name: '子节点1',
value: '50'
}
]
}
]
}
}
}
</script>
自定义展开/折叠功能
手动实现展开折叠功能可以更灵活地控制表格树的交互。
<template>
<table>
<thead>
<tr>
<th></th>
<th>名称</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr v-for="node in flattenedData" :key="node.id">
<td>
<button
v-if="hasChildren(node)"
@click="toggleExpand(node)">
{{ isExpanded(node) ? '-' : '+' }}
</button>
</td>
<td :style="{ paddingLeft: node.level * 20 + 'px' }">
{{ node.name }}
</td>
<td>{{ node.value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
treeData: [...],
expandedNodes: new Set(),
flattenedData: []
}
},
created() {
this.flattenData()
},
methods: {
flattenData(nodes = this.treeData, level = 0) {
nodes.forEach(node => {
this.flattenedData.push({ ...node, level })
if (this.isExpanded(node) && node.children) {
this.flattenData(node.children, level + 1)
}
})
},
toggleExpand(node) {
if (this.expandedNodes.has(node.id)) {
this.expandedNodes.delete(node.id)
} else {
this.expandedNodes.add(node.id)
}
this.flattenedData = []
this.flattenData()
},
isExpanded(node) {
return this.expandedNodes.has(node.id)
},
hasChildren(node) {
return node.children && node.children.length > 0
}
}
}
</script>
性能优化技巧
对于大型树形表格,需要考虑性能优化措施:

- 虚拟滚动:只渲染可视区域内的节点
- 懒加载:当节点展开时才加载子节点数据
- 扁平化数据结构:将树形结构转换为扁平数组并维护展开状态
- 使用
v-if而非v-show控制子节点显示 - 为每个节点设置唯一的
key属性
表格树常见功能实现
- 多选功能:在节点数据中添加
selected属性,配合复选框 - 搜索过滤:对树形数据进行递归过滤
- 拖拽排序:使用HTML5拖拽API或第三方库实现
- 节点编辑:通过v-model绑定节点属性实现编辑功能
- 异步加载:在展开节点时动态请求子节点数据
以上方法可以根据实际需求组合使用,构建功能完善的表格树组件。






