vue实现动态表格
Vue 动态表格实现方法
基础表格结构
使用 v-for 指令循环渲染表格行,数据绑定到数组:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="index">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
rows: [
{ 姓名: '张三', 年龄: 25, 职业: '工程师' },
{ 姓名: '李四', 年龄: 30, 职业: '设计师' }
]
}
}
}
</script>
动态添加/删除行
通过数组方法操作数据实现动态更新:
methods: {
addRow() {
this.rows.push({ 姓名: '', 年龄: 0, 职业: '' })
},
removeRow(index) {
this.rows.splice(index, 1)
}
}
可编辑单元格
结合 v-model 实现单元格编辑功能:
<td v-for="(value, key) in row" :key="key">
<input v-model="row[key]" type="text">
</td>
动态表头配置
支持表头动态配置和自定义渲染:
data() {
return {
headers: [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄', render: (h, { row }) => h('span', row.age + '岁') }
]
}
}
使用计算属性处理数据
对表格数据进行过滤或排序:
computed: {
filteredRows() {
return this.rows.filter(row => row.age > 20)
}
}
组件化实现
将表格封装为可复用组件:
<template>
<dynamic-table :data="tableData" :columns="columns" />
</template>
服务端数据加载
结合 axios 实现异步数据加载:
async created() {
try {
const res = await axios.get('/api/data')
this.rows = res.data
} catch (error) {
console.error(error)
}
}
性能优化
对于大数据量表格使用虚拟滚动:
<virtual-scroller :items="rows" item-height="50">
<template v-slot="{ item }">
<tr>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</template>
</virtual-scroller>
第三方库集成
使用 Element UI 等现成组件库:
<el-table :data="tableData">
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
</el-table>





