用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="(row, index) in rows" :key="index">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '城市'],
rows: [
{ 姓名: '张三', 年龄: 25, 城市: '北京' },
{ 姓名: '李四', 年龄: 30, 城市: '上海' }
]
}
}
}
</script>
添加交互功能
可以通过 Vue 的事件绑定为表格添加排序、筛选等功能:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header" @click="sortBy(header)">
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in sortedRows" :key="index">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '城市'],
rows: [
{ 姓名: '张三', 年龄: 25, 城市: '北京' },
{ 姓名: '李四', 年龄: 30, 城市: '上海' }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedRows() {
if (!this.sortKey) return this.rows
return [...this.rows].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortOrder
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
使用组件库
对于更复杂的需求,可以使用现成的 Vue 表格组件库:
-
Element UI:
<template> <el-table :data="rows"> <el-table-column prop="姓名" label="姓名"></el-table-column> <el-table-column prop="年龄" label="年龄"></el-table-column> <el-table-column prop="城市" label="城市"></el-table-column> </el-table> </template> -
Vuetify:
<template> <v-data-table :headers="headers" :items="rows"></v-data-table> </template> -
Ant Design Vue:
<template> <a-table :columns="headers" :data-source="rows"></a-table> </template>
分页功能实现
可以通过计算属性实现客户端分页:
<template>
<table>
<!-- 表格内容 -->
</table>
<div>
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="currentPage++" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 5,
// 其他数据
}
},
computed: {
paginatedRows() {
const start = (this.currentPage - 1) * this.pageSize
return this.sortedRows.slice(start, start + this.pageSize)
},
totalPages() {
return Math.ceil(this.rows.length / this.pageSize)
}
}
}
</script>
响应式设计
可以通过 CSS 使表格在不同屏幕尺寸下保持良好显示:

table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
@media screen and (max-width: 600px) {
table {
display: block;
overflow-x: auto;
}
}






