vue table实现折叠
Vue Table 实现折叠功能
在 Vue 中实现表格的折叠功能,可以通过动态控制行或列的显示隐藏来实现。以下是几种常见的实现方式:
使用 v-if 或 v-show 控制行显示
通过绑定一个变量来控制行的显示与隐藏。这种方式适合简单的折叠需求。
<template>
<table>
<tr v-for="(item, index) in data" :key="index">
<td>{{ item.name }}</td>
<td>
<button @click="toggleRow(index)">Toggle</button>
</td>
</tr>
<tr v-if="expandedRows.includes(index)">
<td colspan="2">{{ item.details }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
data: [...], // 你的数据
expandedRows: []
}
},
methods: {
toggleRow(index) {
if (this.expandedRows.includes(index)) {
this.expandedRows = this.expandedRows.filter(i => i !== index);
} else {
this.expandedRows.push(index);
}
}
}
}
</script>
使用组件库实现
许多 Vue 组件库如 Element UI、Ant Design Vue 等提供了内置的折叠表格功能。
以 Element UI 为例:
<template>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column type="expand">
<template #default="props">
<p>Details: {{ props.row.detail }}</p>
</template>
</el-table-column>
<el-table-column
label="Name"
prop="name">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
name: 'Item 1',
detail: 'Detail info 1'
}, {
name: 'Item 2',
detail: 'Detail info 2'
}]
}
}
}
</script>
使用 CSS 过渡效果
可以为折叠行添加过渡效果,提升用户体验。
<template>
<table>
<tr v-for="(item, index) in data" :key="index">
<td>{{ item.name }}</td>
<td>
<button @click="toggleRow(index)">Toggle</button>
</td>
</tr>
<tr v-show="expandedRows.includes(index)" class="expandable">
<td colspan="2">{{ item.details }}</td>
</tr>
</table>
</template>
<style>
.expandable {
transition: all 0.3s ease;
}
</style>
嵌套表格实现多级折叠
对于需要多级折叠的复杂表格,可以使用嵌套表格的方式。
<template>
<table>
<tr v-for="(item, index) in data" :key="index">
<td>
<button @click="toggleRow(index)">{{ expandedRows.includes(index) ? '-' : '+' }}</button>
</td>
<td>{{ item.name }}</td>
</tr>
<tr v-if="expandedRows.includes(index)">
<td colspan="2">
<table>
<tr v-for="(subItem, subIndex) in item.children" :key="subIndex">
<td>{{ subItem.name }}</td>
</tr>
</table>
</td>
</tr>
</table>
</template>
使用第三方插件
对于更复杂的需求,可以考虑使用专门处理表格的 Vue 插件,如 vue-good-table 或 ag-grid-vue。
以 vue-good-table 为例:
<template>
<vue-good-table
:columns="columns"
:rows="rows"
:expand-rows="true">
<template #table-row="props">
<span v-if="props.column.field == 'details'">
{{ props.row.details }}
</span>
</template>
</vue-good-table>
</template>
<script>
import { VueGoodTable } from 'vue-good-table';
export default {
components: {
VueGoodTable
},
data() {
return {
columns: [
{ label: 'Name', field: 'name' },
{ label: 'Details', field: 'details' }
],
rows: [
{ name: 'Item 1', details: 'Detail 1' },
{ name: 'Item 2', details: 'Detail 2' }
]
}
}
}
</script>
以上方法可以根据实际需求选择使用,从简单的显示隐藏到复杂的多级折叠都能实现。组件库提供的方法通常更简单快捷,而自定义实现则更加灵活。







