vue实现子表格
Vue 实现子表格的方法
在 Vue 中实现子表格可以通过多种方式完成,以下是几种常见的方法:
使用嵌套组件
创建一个父表格组件和一个子表格组件,通过 props 将数据传递给子表格组件。父表格的每一行可以展开显示子表格。
<template>
<table>
<thead>
<tr>
<th>主表头</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in mainData" :key="index">
<td>
{{ row.mainField }}
<button @click="toggleSubTable(index)">展开</button>
<sub-table v-if="expandedRows[index]" :data="row.subData"/>
</td>
</tr>
</tbody>
</table>
</template>
<script>
import SubTable from './SubTable.vue';
export default {
components: { SubTable },
data() {
return {
expandedRows: {},
mainData: [
{ mainField: '数据1', subData: [...] },
// 更多数据...
]
};
},
methods: {
toggleSubTable(index) {
this.$set(this.expandedRows, index, !this.expandedRows[index]);
}
}
};
</script>
使用 Element UI 的 Table 组件
如果使用 Element UI,可以利用其提供的 expandable rows 功能实现子表格。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="expand">
<template #default="props">
<el-table :data="props.row.children">
<el-table-column prop="date" label="子表日期"/>
<el-table-column prop="name" label="子表名称"/>
</el-table>
</template>
</el-table-column>
<el-table-column prop="date" label="主表日期"/>
<el-table-column prop="name" label="主表名称"/>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2023-01-01',
name: '主数据1',
children: [{
date: '2023-01-02',
name: '子数据1'
}]
}]
};
}
};
</script>
使用动态组件
通过动态组件的方式切换显示子表格,适用于更复杂的交互场景。
<template>
<table>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>
<button @click="showDetail(index)">详情</button>
<component
:is="currentComponent"
v-if="activeIndex === index"
:data="item.details"
/>
</td>
</tr>
</table>
</template>
<script>
import DetailTable from './DetailTable.vue';
export default {
components: { DetailTable },
data() {
return {
items: [...],
activeIndex: null,
currentComponent: 'DetailTable'
};
},
methods: {
showDetail(index) {
this.activeIndex = index;
}
}
};
</script>
使用 CSS 控制显示/隐藏
通过 CSS 和 v-show 指令控制子表格的显示与隐藏,适用于简单的展示需求。
<template>
<table>
<tr v-for="(item, index) in data" :key="index" class="parent-row">
<td>{{ item.name }}</td>
<td>
<button @click="toggleChildren(index)">展开</button>
</td>
</tr>
<tr v-show="expandedRows[index]" class="child-row" v-for="(child, childIndex) in item.children" :key="childIndex">
<td colspan="2">
<table>
<tr>
<td>{{ child.name }}</td>
</tr>
</table>
</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
data: [...],
expandedRows: {}
};
},
methods: {
toggleChildren(index) {
this.$set(this.expandedRows, index, !this.expandedRows[index]);
}
}
};
</script>
注意事项
- 数据嵌套结构要合理,避免过深的层级影响性能。
- 子表格的展开/收起状态需要妥善管理,避免不必要的渲染。
- 对于大数据量的表格,考虑使用虚拟滚动优化性能。
以上方法可以根据具体需求选择使用,Element UI 等组件库提供了更完善的功能和样式,适合快速开发。







