表格用vue实现
使用 Vue 实现表格
基础表格实现
通过 v-for 指令动态渲染表格数据是最基础的方式。假设有一个数据数组 tableData,可以这样实现:
<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>
动态绑定属性
如果需要动态绑定样式或事件,可以通过 :class 或 @click 实现:
<tr v-for="(row, rowIndex) in tableData"
:key="rowIndex"
:class="{ 'active': row.isActive }"
@click="handleRowClick(row)">
<td v-for="(cell, cellIndex) in row.cells" :key="cellIndex">{{ cell }}</td>
</tr>
使用组件库
对于复杂需求,推荐使用现成的 Vue 表格组件库:

-
Element 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> -
VxeTable:功能强大的高级表格

<vxe-table :data="tableData"> <vxe-column field="name" title="姓名"></vxe-column> <vxe-column field="age" title="年龄"></vxe-column> </vxe-table>
性能优化
当数据量较大时,建议使用虚拟滚动技术:
- 使用
vue-virtual-scroller插件<RecycleScroller class="table-body" :items="tableData" :item-size="50" key-field="id" > <template v-slot="{ item }"> <tr> <td>{{ item.name }}</td> <td>{{ item.age }}</td> </tr> </template> </RecycleScroller>
服务端分页
结合后端 API 实现分页功能:
methods: {
async fetchData(page = 1) {
const res = await api.get('/data', { params: { page } })
this.tableData = res.data
this.total = res.total
}
}
自定义渲染
通过插槽实现复杂单元格内容:
<el-table-column label="操作">
<template #default="{ row }">
<el-button @click="edit(row)">编辑</el-button>
</template>
</el-table-column>
以上方法涵盖了从基础到进阶的 Vue 表格实现方式,开发者可以根据项目需求选择合适的技术方案。






