vue table实现折叠
Vue 表格折叠实现方法
使用 Element UI 的 el-table 组件
Element UI 的 el-table 组件内置了展开行功能,通过 type="expand" 和 scoped-slot 实现。
<template>
<el-table :data="tableData">
<el-table-column type="expand">
<template #default="props">
<p>详细信息: {{ props.row.desc }}</p>
</template>
</el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20, desc: '这是张三的详细信息' },
{ name: '李四', age: 22, desc: '这是李四的详细信息' }
]
}
}
}
</script>
自定义折叠实现
对于非 Element UI 项目,可以通过 v-show/v-if 和点击事件实现折叠效果。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="toggleExpand(item.id)">
{{ expandedRows.includes(item.id) ? '收起' : '展开' }}
</button>
</td>
</tr>
<tr v-for="item in tableData"
v-show="expandedRows.includes(item.id)"
:key="'detail-' + item.id">
<td colspan="3">
{{ item.desc }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 20, desc: '详细信息...' },
{ id: 2, name: '李四', age: 22, desc: '详细信息...' }
],
expandedRows: []
}
},
methods: {
toggleExpand(id) {
const index = this.expandedRows.indexOf(id)
if (index > -1) {
this.expandedRows.splice(index, 1)
} else {
this.expandedRows.push(id)
}
}
}
}
</script>
使用第三方组件库
一些 Vue 表格组件库如 VxeTable、Ant Design Vue 等也提供了折叠功能:
VxeTable 示例:
<template>
<vxe-table :data="tableData">
<vxe-column type="expand" width="60">
<template #content="{ row }">
<div>{{ row.desc }}</div>
</template>
</vxe-column>
<vxe-column field="name" title="姓名"></vxe-column>
<vxe-column field="age" title="年龄"></vxe-column>
</vxe-table>
</template>
动画过渡效果
为折叠添加动画效果,可以使用 Vue 的 transition 组件:

<transition name="fade">
<tr v-if="expandedRows.includes(item.id)">
<td colspan="3">
{{ item.desc }}
</td>
</tr>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






