vue实现表格读取数据
使用 Vue 实现表格数据读取
基础表格数据绑定
通过 v-for 指令遍历数组数据,动态生成表格行。数据通常存储在组件的 data 属性中。
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
]
}
}
}
</script>
从 API 异步加载数据
使用 axios 或 fetch 从后端接口获取数据,更新表格内容。

<script>
import axios from 'axios';
export default {
data() {
return {
tableData: []
}
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
axios.get('/api/users')
.then(response => {
this.tableData = response.data;
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
}
</script>
使用计算属性处理数据
对表格数据进行过滤或排序时,推荐使用计算属性避免直接修改原始数据。

computed: {
sortedData() {
return [...this.tableData].sort((a, b) => a.age - b.age);
}
}
添加分页功能
通过 v-model 绑定分页参数,切片显示数据。
<template>
<div>
<table>...</table>
<div class="pagination">
<button @click="currentPage--" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="currentPage++" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
allData: []
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
return this.allData.slice(start, start + this.pageSize);
},
totalPages() {
return Math.ceil(this.allData.length / this.pageSize);
}
}
}
</script>
使用第三方表格组件
对于复杂需求,可集成现成组件库如 Element UI 或 Vuetify。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="ID" width="180"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
</el-table>
</template>






