vue 实现简单表格
基础表格实现
使用 Vue 的 v-for 指令动态渲染表格数据,结合 el-table(Element UI)或原生 HTML 表格。
示例代码(原生 HTML 表格)
<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="(value, key) in row" :key="key">{{ value }}</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="80"></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>
动态数据绑定
通过 API 请求动态加载表格数据,结合 axios 或其他 HTTP 库。

示例代码
<template>
<el-table :data="tableData" v-loading="isLoading">
<!-- 列定义 -->
</el-table>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData: [],
isLoading: false
};
},
async created() {
this.isLoading = true;
try {
const response = await axios.get('https://api.example.com/data');
this.tableData = response.data;
} catch (error) {
console.error('Error fetching data:', error);
} finally {
this.isLoading = false;
}
}
};
</script>
表格功能扩展
- 分页:使用
el-pagination与el-table结合。 - 排序:在
el-table-column中设置sortable属性。 - 筛选:通过
scoped slots自定义筛选逻辑。
分页示例
<template>
<el-table :data="pagedData">
<!-- 列定义 -->
</el-table>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="tableData.length">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
tableData: [] // 原始数据
};
},
computed: {
pagedData() {
const start = (this.currentPage - 1) * this.pageSize;
return this.tableData.slice(start, start + this.pageSize);
}
},
methods: {
handlePageChange(page) {
this.currentPage = page;
}
}
};
</script>






