vue实现表格树
Vue 实现表格树的方法
在 Vue 中实现表格树可以通过递归组件或第三方库(如 Element UI 或 Ant Design Vue)来完成。以下是几种常见的实现方式:
使用递归组件
递归组件是 Vue 中实现树形结构的常见方式。通过组件调用自身,可以轻松实现多层嵌套的表格树。

<template>
<table>
<thead>
<tr>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tree-node v-for="node in treeData" :key="node.id" :node="node"></tree-node>
</tbody>
</table>
</template>
<script>
import TreeNode from './TreeNode.vue';
export default {
components: { TreeNode },
data() {
return {
treeData: [
{
id: 1,
name: '节点1',
children: [
{ id: 2, name: '子节点1' },
{ id: 3, name: '子节点2' }
]
}
]
};
}
};
</script>
在 TreeNode.vue 中递归调用自身:

<template>
<tr>
<td>{{ node.name }}</td>
<td>
<button @click="toggleChildren">展开/折叠</button>
</td>
</tr>
<tr v-if="showChildren && node.children">
<td colspan="2">
<table>
<tbody>
<tree-node
v-for="child in node.children"
:key="child.id"
:node="child"
></tree-node>
</tbody>
</table>
</td>
</tr>
</template>
<script>
export default {
name: 'TreeNode',
props: ['node'],
data() {
return {
showChildren: false
};
},
methods: {
toggleChildren() {
this.showChildren = !this.showChildren;
}
}
};
</script>
使用 Element UI 的树形表格
Element UI 提供了 el-table 和 el-tree 组件,可以结合使用实现树形表格。
<template>
<el-table
:data="tableData"
row-key="id"
:tree-props="{ children: 'children' }"
>
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="operation" label="操作"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{
id: 1,
name: '节点1',
children: [
{ id: 2, name: '子节点1' },
{ id: 3, name: '子节点2' }
]
}
]
};
}
};
</script>
使用 Ant Design Vue 的树形表格
Ant Design Vue 的 a-table 组件也支持树形表格功能。
<template>
<a-table
:columns="columns"
:data-source="data"
:row-key="record => record.id"
:pagination="false"
:expand-icon-column-index="1"
>
<template #operation>
<a-button>操作</a-button>
</template>
</a-table>
</template>
<script>
export default {
data() {
return {
columns: [
{ title: '名称', dataIndex: 'name' },
{ title: '操作', slots: { customRender: 'operation' } }
],
data: [
{
id: 1,
name: '节点1',
children: [
{ id: 2, name: '子节点1' },
{ id: 3, name: '子节点2' }
]
}
]
};
}
};
</script>
注意事项
- 递归组件需要注意性能问题,避免过深的嵌套层级。
- 使用第三方库时,确保引入正确的版本和样式文件。
- 树形表格的数据结构通常包含
children字段,用于表示子节点。






