vue实现表格渲染
Vue 实现表格渲染的方法
基础表格渲染
使用 v-for 指令遍历数据数组,动态生成表格行。数据通常存储在组件的 data 属性中。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
动态表头渲染
当表头需要动态生成时,可以用 v-for 遍历表头数组。
<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>
使用计算属性处理数据
当需要对表格数据进行过滤或排序时,可以使用计算属性。
export default {
data() {
return {
rawData: [
{ name: '张三', score: 85 },
{ name: '李四', score: 92 }
]
}
},
computed: {
sortedData() {
return [...this.rawData].sort((a, b) => b.score - a.score)
}
}
}
表格分页功能
实现分页需要计算当前页显示的数据片段。
export default {
data() {
return {
tableData: [...],
currentPage: 1,
pageSize: 5
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
return this.tableData.slice(start, start + this.pageSize)
},
totalPages() {
return Math.ceil(this.tableData.length / this.pageSize)
}
}
}
使用第三方表格组件
对于复杂需求,可以使用现成的表格组件库如 Element UI 或 Vuetify。
<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>
</template>
性能优化技巧
对于大型数据集,建议使用虚拟滚动技术避免渲染所有行。可以借助 vue-virtual-scroller 等库实现。
<template>
<RecycleScroller
class="table-body"
:items="tableData"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<tr>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</RecycleScroller>
</template>






