vue实现表
Vue 实现表格的基本方法
使用 Vue 实现表格可以通过多种方式,包括原生 HTML 表格、第三方组件库(如 Element UI、Ant Design Vue)或自定义组件。以下是几种常见实现方式:
原生 HTML 表格
通过 v-for 指令循环渲染表格数据:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['ID', 'Name', 'Age'],
rows: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
使用 Element UI 表格组件
安装 Element UI 后直接使用 el-table:
<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>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
表格功能扩展
分页功能
结合 el-pagination 实现分页:
<template>
<div>
<el-table :data="currentPageData"></el-table>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="tableData.length">
</el-pagination>
</div>
</template>
<script>
export default {
computed: {
currentPageData() {
const start = (this.currentPage - 1) * this.pageSize
return this.tableData.slice(start, start + this.pageSize)
}
}
}
</script>
排序功能
通过 sortable 属性启用列排序:
<el-table-column prop="age" label="Age" sortable></el-table-column>
自定义表格组件
创建可复用的表格组件:
<!-- TableComponent.vue -->
<template>
<table>
<slot name="header"></slot>
<slot name="body" :rows="rows"></slot>
</table>
</template>
<script>
export default {
props: ['rows']
}
</script>
使用时通过插槽自定义内容:

<TableComponent :rows="tableData">
<template #header>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</template>
<template #body="{ rows }">
<tr v-for="row in rows" :key="row.id">
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
</tr>
</template>
</TableComponent>






