vue动态表格实现
Vue 动态表格实现方法
基础实现:基于 v-for 动态渲染
通过 v-for 指令动态生成表格行和列,数据源通常为数组对象:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="col in columns" :key="col.key">{{ row[col.key] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: [
{ key: 'name', title: '姓名' },
{ key: 'age', title: '年龄' }
],
data: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
动态列配置
通过计算属性或方法动态处理列显示逻辑:
computed: {
filteredColumns() {
return this.columns.filter(col => !col.hidden)
}
}
可编辑表格实现
结合 v-model 实现单元格编辑功能:
<td v-for="col in columns" :key="col.key">
<input
v-if="editable && col.editable"
v-model="row[col.key]"
@blur="saveEdit(row)"
>
<span v-else>{{ row[col.key] }}</span>
</td>
使用第三方组件库
Element UI 实现方案:
<el-table :data="tableData" style="width: 100%">
<el-table-column
v-for="col in columns"
:prop="col.prop"
:label="col.label"
:width="col.width"
>
</el-table-column>
</el-table>
性能优化建议
大数据量场景下建议使用虚拟滚动:
import { RecycleScroller } from 'vue-virtual-scroller'
动态表头与数据绑定
实现表头与数据的动态关联:

methods: {
addColumn() {
const newKey = `column_${this.columns.length + 1}`
this.columns.push({ key: newKey, title: `列${this.columns.length + 1}` })
this.data.forEach(item => {
item[newKey] = ''
})
}
}
注意事项
- 始终为动态元素设置
:key - 复杂表格建议拆分为子组件
- 超过 1000 行数据需考虑分页或虚拟滚动方案
- 可编辑表格应做好数据验证






