实现vue table
实现 Vue 表格的基础方法
使用 Vue 实现表格功能可以通过原生 HTML 表格结合 Vue 的数据绑定,或者使用第三方组件库(如 Element UI、Vuetify)快速构建。以下是几种常见方法:
使用原生 HTML 和 Vue 数据绑定
通过 v-for 指令动态渲染表格数据:

<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in tableData" :key="row.id">
<td v-for="cell in row" :key="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ["ID", "Name", "Age"],
tableData: [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
],
};
},
};
</script>
使用 Element UI 的表格组件
Element UI 提供 <el-table> 组件,支持排序、分页、筛选等功能:

<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="ID" width="100"></el-table-column>
<el-table-column prop="name" label="Name" width="180"></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>
使用 Vuetify 的表格组件
Vuetify 的 <v-data-table> 提供高度可定制的表格功能:
<template>
<v-data-table :headers="headers" :items="tableData"></v-data-table>
</template>
<script>
export default {
data() {
return {
headers: [
{ text: "ID", value: "id" },
{ text: "Name", value: "name" },
{ text: "Age", value: "age" },
],
tableData: [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
],
};
},
};
</script>
自定义表格功能
如果需要自定义功能(如编辑单元格、动态列渲染),可以结合计算属性和方法:
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="row.id">
<td v-for="(cell, key) in row" :key="key">
<input v-if="editableRow === index" v-model="row[key]" />
<span v-else>{{ cell }}</span>
</td>
<td>
<button @click="toggleEdit(index)">
{{ editableRow === index ? "Save" : "Edit" }}
</button>
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ["ID", "Name", "Age"],
tableData: [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
],
editableRow: null,
};
},
methods: {
toggleEdit(index) {
this.editableRow = this.editableRow === index ? null : index;
},
},
};
</script>
表格优化建议
- 分页:使用
v-pagination(Vuetify)或<el-pagination>(Element UI)实现分页。 - 排序:在表头添加
@click事件,结合Array.sort()动态排序数据。 - 筛选:通过计算属性过滤数据,例如
filteredData。 - 虚拟滚动:对于大数据量,使用
vue-virtual-scroller优化性能。
以上方法可根据项目需求选择原生实现或组件库集成。






