vue 实现表格渲染
基本表格渲染
在 Vue 中渲染表格通常使用 v-for 指令遍历数据数组,动态生成表格行。以下是一个简单的示例:
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.job }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 28, job: '工程师' },
{ name: '李四', age: 32, job: '设计师' }
]
}
}
}
</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>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
tableData: [
['张三', 28, '工程师'],
['李四', 32, '设计师']
]
}
}
}
</script>
使用计算属性处理数据
对于需要复杂处理的数据,可以使用计算属性:
<template>
<table>
<tr v-for="(item, index) in processedData" :key="index">
<td>{{ item.fullName }}</td>
<td>{{ item.ageGroup }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
rawData: [
{ firstName: '张', lastName: '三', age: 28 },
{ firstName: '李', lastName: '四', age: 32 }
]
}
},
computed: {
processedData() {
return this.rawData.map(item => ({
fullName: `${item.firstName}${item.lastName}`,
ageGroup: item.age > 30 ? '中年' : '青年'
}))
}
}
}
</script>
组件化表格
对于复用场景,可将表格封装为组件:
<!-- TableComponent.vue -->
<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>
<!-- 使用方式 -->
<template>
<TableComponent :data="tableData">
<template #header>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
</template>
<template #default="{ row }">
<td>{{ row.name }}</td>
<td>{{ row.age }}</td>
</template>
</TableComponent>
</template>
第三方表格组件
对于复杂需求,可以使用现成的表格组件库:
-
Element UI 的
el-table:<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>
性能优化
大数据量渲染时建议使用虚拟滚动:
<template>
<RecycleScroller
class="table-body"
:items="tableData"
:item-size="50"
key-field="id"
>
<template #default="{ item }">
<tr>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
export default {
components: { RecycleScroller },
data() {
return {
tableData: [] // 大数据量
}
}
}
</script>






