vue实现表格组件
Vue 表格组件实现方法
基础表格实现
使用<table>标签结合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>
使用第三方组件库
Element UI的表格组件提供丰富功能:
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column prop="job" label="职业"></el-table-column>
</el-table>
</template>
自定义可编辑表格
实现单元格编辑功能需结合v-model:
<template>
<table>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, colIndex) in row" :key="colIndex">
<input v-if="editable[rowIndex][colIndex]" v-model="tableData[rowIndex][colIndex]">
<span v-else @click="editCell(rowIndex, colIndex)">{{ cell }}</span>
</td>
</tr>
</table>
</template>
<script>
export default {
methods: {
editCell(row, col) {
this.$set(this.editable[row], col, true)
}
}
}
</script>
分页功能实现
结合分页组件控制数据展示:
<template>
<div>
<table>...</table>
<div class="pagination">
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<span>第{{ currentPage }}页</span>
<button @click="currentPage++" :disabled="currentPage >= totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
return this.tableData.slice(start, start + this.pageSize)
}
}
}
</script>
性能优化建议
大数据量时使用虚拟滚动技术:

import { RecycleScroller } from 'vue-virtual-scroller'
export default {
components: { RecycleScroller },
template: `
<RecycleScroller :items="tableData" :item-size="50">
<template v-slot="{ item }">
<tr>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</template>
</RecycleScroller>
`
}
注意事项
- 始终为
v-for设置唯一的key属性 - 复杂表格建议拆分为多个子组件
- 超过1000行数据应考虑分页或虚拟滚动方案
- 可复用组件应通过props接收数据和配置参数






