vue表格组件实现
Vue 表格组件实现
基础表格实现
使用 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 items" :key="item.id">
<td v-for="header in headers" :key="header">{{ item[header] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['name', 'age', 'gender'],
items: [
{ id: 1, name: 'Alice', age: 25, gender: 'Female' },
{ id: 2, name: 'Bob', age: 30, gender: 'Male' }
]
}
}
}
</script>
可排序表格
通过添加排序功能增强表格交互性:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers"
:key="header.key"
@click="sortBy(header.key)">
{{ header.text }}
<span v-if="sortKey === header.key">
{{ sortOrder > 0 ? '↑' : '↓' }}
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedItems" :key="item.id">
<td v-for="header in headers" :key="header.key">{{ item[header.key] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
sortKey: '',
sortOrder: 1,
headers: [
{ key: 'name', text: 'Name' },
{ key: 'age', text: 'Age' }
],
items: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
},
computed: {
sortedItems() {
const key = this.sortKey
const order = this.sortOrder
return [...this.items].sort((a, b) => {
return (a[key] > b[key] ? 1 : -1) * order
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
分页功能
为大型数据集添加分页支持:
<template>
<div>
<table><!-- 表格内容同上 --></table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
items: [/* 数据数组 */]
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
return this.items.slice(start, start + this.itemsPerPage)
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
},
prevPage() {
if (this.currentPage > 1) this.currentPage--
}
}
}
</script>
使用第三方组件库
对于更复杂的需求,可以考虑使用专业表格组件库:
- Vuetify 的
v-data-table:提供排序、分页、搜索等开箱即用功能 - Element UI 的
el-table:支持树形数据、固定列等高级功能 - Ant Design Vue 的
a-table:适用于企业级应用
性能优化技巧
对于大型数据集渲染:

- 使用虚拟滚动技术(如 vue-virtual-scroller)
- 实现懒加载数据
- 避免不必要的响应式数据
- 使用计算属性缓存计算结果






