vue怎么实现动态表格
Vue 动态表格实现方法
基于 v-for 的数据驱动渲染
通过 v-for 指令循环渲染表格行和列,数据变化时表格自动更新:
<template>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
tableData: [
['张三', 25, '工程师'],
['李四', 30, '设计师']
]
}
}
}
</script>
动态列配置
使用计算属性处理动态列显示逻辑:
computed: {
visibleColumns() {
return this.columns.filter(col => !col.hidden)
}
}
模板部分适配动态列:
<th v-for="col in visibleColumns" :key="col.prop">{{ col.label }}</th>
<td v-for="col in visibleColumns" :key="col.prop">{{ row[col.prop] }}</td>
可编辑表格实现
通过 v-model 绑定单元格数据:

<td v-for="col in columns" :key="col.prop">
<input v-if="col.editable" v-model="row[col.prop]">
<span v-else>{{ row[col.prop] }}</span>
</td>
动态行操作
添加行删除功能示例:
methods: {
removeRow(index) {
this.tableData.splice(index, 1)
}
}
模板中添加操作按钮:

<td>
<button @click="removeRow(rowIndex)">删除</button>
</td>
使用第三方组件库
Element UI 实现示例:
<el-table :data="tableData">
<el-table-column v-for="col in columns"
:prop="col.prop"
:label="col.label"
:key="col.prop">
</el-table-column>
</el-table>
性能优化建议
大数据量时使用虚拟滚动:
<vue-virtual-scroller :items="largeData" :item-height="50">
<template v-slot="{ item }">
<tr>
<td v-for="col in columns" :key="col.prop">{{ item[col.prop] }}</td>
</tr>
</template>
</vue-virtual-scroller>
动态表头合并
复杂表头处理示例:
<thead>
<tr>
<th :colspan="2">基本信息</th>
<th :colspan="3">详细信息</th>
</tr>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>部门</th>
<th>职位</th>
<th>入职日期</th>
</tr>
</thead>





