vue实现表格报表
Vue 实现表格报表的方法
使用 Element UI 表格组件
Element UI 提供了强大的表格组件,支持排序、筛选、分页等功能。安装 Element UI 后,可以直接使用 el-table 组件。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ date: '2023-01-01', name: '张三', address: '北京市' },
{ date: '2023-01-02', name: '李四', address: '上海市' }
]
}
}
}
</script>
使用 VxeTable 高级表格
VxeTable 是一个功能更丰富的表格库,支持虚拟滚动、编辑、导出等功能。
<template>
<vxe-table :data="tableData">
<vxe-column type="seq" title="序号" width="60"></vxe-column>
<vxe-column field="date" title="日期"></vxe-column>
<vxe-column field="name" title="姓名"></vxe-column>
<vxe-column field="address" title="地址"></vxe-column>
</vxe-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ date: '2023-01-01', name: '张三', address: '北京市' },
{ date: '2023-01-02', name: '李四', address: '上海市' }
]
}
}
}
</script>
自定义表格组件
如果需要更灵活的表格,可以手动实现一个表格组件。通过 v-for 动态渲染表头和表格数据。
<template>
<table class="custom-table">
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="col in columns" :key="col.key">{{ row[col.key] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
columns: Array,
data: Array
}
}
</script>
<style>
.custom-table {
width: 100%;
border-collapse: collapse;
}
.custom-table th, .custom-table td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
数据导出为 Excel
使用 xlsx 库可以将表格数据导出为 Excel 文件。
<template>
<button @click="exportExcel">导出 Excel</button>
<el-table :data="tableData" ref="table">
<!-- 表格列定义 -->
</el-table>
</template>
<script>
import XLSX from 'xlsx';
export default {
methods: {
exportExcel() {
const table = this.$refs.table.$el;
const workbook = XLSX.utils.table_to_book(table);
XLSX.writeFile(workbook, '报表.xlsx');
}
}
}
</script>
动态加载数据
通过 API 动态加载表格数据,结合分页和加载状态。

<template>
<el-table :data="tableData" v-loading="loading">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
></el-pagination>
</template>
<script>
export default {
data() {
return {
tableData: [],
loading: false,
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
fetchData() {
this.loading = true;
axios.get('/api/data', { params: { page: this.currentPage, size: this.pageSize } })
.then(res => {
this.tableData = res.data.list;
this.total = res.data.total;
})
.finally(() => this.loading = false);
},
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
}
},
created() {
this.fetchData();
}
}
</script>
注意事项
- 性能优化:大数据量时考虑虚拟滚动或分页加载。
- 响应式设计:确保表格在不同设备上显示正常。
- 可访问性:为表格添加适当的 ARIA 属性。






