vue数据绑定实现表格
Vue 数据绑定实现表格的方法
基础表格绑定
使用 v-for 指令循环渲染表格行,绑定动态数据到表格单元格:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td v-for="(value, key) in item" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '城市'],
tableData: [
{ 姓名: '张三', 年龄: 25, 城市: '北京' },
{ 姓名: '李四', 年龄: 30, 城市: '上海' }
]
}
}
}
</script>
动态属性绑定
为表格元素添加动态样式或属性:
<tr v-for="item in tableData"
:class="{ 'active-row': item.isActive }"
@click="selectRow(item)">
<td>{{ item.name }}</td>
</tr>
计算属性处理数据
使用计算属性对表格数据进行处理:

computed: {
filteredData() {
return this.tableData.filter(item => item.age > 25)
}
}
使用组件化表格
创建可复用的表格组件:
<template>
<table>
<slot name="header"></slot>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<slot :row="item"></slot>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: ['data']
}
</script>
服务端数据绑定
结合 axios 获取远程数据:

import axios from 'axios'
export default {
data() {
return {
tableData: []
}
},
mounted() {
axios.get('/api/data').then(response => {
this.tableData = response.data
})
}
}
使用第三方表格组件
集成 Element UI 等 UI 库的表格组件:
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
响应式更新
确保数据变化时表格自动更新:
this.$set(this.tableData, index, newItem)
// 或
this.tableData.splice(index, 1, newItem)
性能优化
对于大型数据集使用虚拟滚动:
<virtual-list :size="50" :remain="20" :data="largeData">
<table>
<tr v-for="item in virtualData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</virtual-list>






