vue 表格实现
Vue 表格实现方法
基础表格实现
使用原生HTML表格标签结合Vue数据绑定实现基础表格。通过v-for指令循环渲染表格行,动态绑定表格数据。
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td v-for="(value, key) in item" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['ID', 'Name', 'Age'],
tableData: [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 }
]
}
}
}
</script>
使用第三方组件库
Element UI、Ant Design Vue等流行UI库提供功能丰富的表格组件,支持排序、分页、筛选等高级功能。
Element UI示例:

<template>
<el-table :data="tableData">
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
</template>
自定义表格组件
创建可复用的表格组件,通过props接收数据和配置,实现高度定制化。
<!-- TableComponent.vue -->
<template>
<table>
<slot name="header"></slot>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<slot :item="item"></slot>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
data: Array
}
}
</script>
表格功能扩展
实现排序功能可以通过计算属性对数据进行处理,添加排序按钮触发排序逻辑。

computed: {
sortedData() {
return [...this.tableData].sort((a, b) => {
return this.sortOrder * (a[this.sortKey] > b[this.sortKey] ? 1 : -1)
})
}
},
methods: {
sortBy(key) {
this.sortKey = key
this.sortOrder = -this.sortOrder
}
}
性能优化
对于大数据量表格,使用虚拟滚动技术避免渲染所有行,只渲染可视区域内的行。
<template>
<div class="virtual-table" @scroll="handleScroll">
<div class="table-content" :style="{ height: totalHeight }">
<div v-for="item in visibleData" :key="item.id" class="table-row">
<!-- 行内容 -->
</div>
</div>
</div>
</template>
响应式设计
通过CSS媒体查询或JavaScript监听窗口大小变化,调整表格布局以适应不同屏幕尺寸。
@media (max-width: 768px) {
table {
display: block;
overflow-x: auto;
}
}






