vue动态实现表
Vue 动态表格实现方法
数据驱动渲染
通过 v-for 指令绑定数组数据动态生成表格行
<template>
<table>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
]
}
}
}
</script>
动态表头配置
使用计算属性处理表头数据
computed: {
headers() {
return [
{ text: '姓名', value: 'name' },
{ text: '年龄', value: 'age' }
]
}
}
可编辑单元格
结合 v-model 实现双向绑定

<td v-for="header in headers" :key="header.value">
<input v-model="item[header.value]" />
</td>
动态列渲染
根据配置动态决定显示列
methods: {
toggleColumn(col) {
this.visibleColumns = this.visibleColumns.includes(col)
? this.visibleColumns.filter(c => c !== col)
: [...this.visibleColumns, col]
}
}
性能优化
对于大数据量使用虚拟滚动

<virtual-scroller :items="largeData" item-height="50">
<template v-slot="{ item }">
<tr>
<td>{{ item.id }}</td>
<td>{{ item.content }}</td>
</tr>
</template>
</virtual-scroller>
服务端分页
配合 axios 实现分页加载
async fetchData(page) {
const res = await axios.get(`/api/data?page=${page}`)
this.tableData = res.data.items
this.total = res.data.total
}
响应式设计
通过 CSS 媒体查询适配不同屏幕
@media (max-width: 768px) {
table {
display: block;
overflow-x: auto;
}
}






