vue table实现折叠
vue table 实现折叠
使用 el-table 的 expand 功能结合 scoped slot 实现折叠展开效果。以下是一个完整示例:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="expand">
<template #default="props">
<p>姓名: {{ props.row.name }}</p>
<p>地址: {{ props.row.address }}</p>
</template>
</el-table-column>
<el-table-column label="日期" prop="date"></el-table-column>
<el-table-column label="姓名" prop="name"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
},
{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}
]
}
}
}
</script>
自定义折叠图标
通过 expand-change 事件和 row-key 属性控制折叠状态:
<template>
<el-table
:data="tableData"
row-key="id"
@expand-change="handleExpand"
>
<el-table-column type="expand">
<template #default="props">
<div v-if="props.row.expand">
<p>详细信息: {{ props.row.detail }}</p>
</div>
</template>
</el-table-column>
<!-- 其他列 -->
</el-table>
</template>
<script>
export default {
methods: {
handleExpand(row, expandedRows) {
console.log(row, expandedRows)
}
}
}
</script>
手风琴效果折叠
只允许同时展开一行:
<template>
<el-table
:data="tableData"
:row-key="row => row.id"
@expand-change="handleExpand"
>
<!-- 列定义 -->
</el-table>
</template>
<script>
export default {
data() {
return {
currentExpandRow: null
}
},
methods: {
handleExpand(row, expandedRows) {
if (expandedRows.length > 1) {
this.$refs.table.toggleRowExpansion(expandedRows[0])
}
this.currentExpandRow = row
}
}
}
</script>
动态加载折叠内容
展开时异步加载数据:

<template>
<el-table :data="tableData">
<el-table-column type="expand">
<template #default="props">
<div v-if="props.row.loaded">
<p>{{ props.row.detail }}</p>
</div>
<div v-else>加载中...</div>
</template>
</el-table-column>
<!-- 其他列 -->
</el-table>
</template>
<script>
export default {
methods: {
loadDetail(row) {
// 模拟异步请求
setTimeout(() => {
row.detail = '这是动态加载的详细内容'
row.loaded = true
this.$forceUpdate()
}, 1000)
},
handleExpand(row) {
if (!row.loaded) {
this.loadDetail(row)
}
}
}
}
</script>
注意事项
- 使用
row-key确保每行有唯一标识 - 动态数据更新后可能需要调用
$forceUpdate() - 折叠内容样式可通过 CSS 自定义
- 大量数据时考虑性能优化
以上实现方式适用于 Element UI 的表格组件,其他 UI 库实现原理类似,具体 API 可能有所不同。






