vue实现表格分页
实现表格分页的基础方法
在Vue中实现表格分页通常需要结合数据分片和分页组件。基本思路是将数据按页分割,通过计算属性或方法动态获取当前页的数据。
模板部分示例:
<template>
<div>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="item in paginatedData" :key="item.id">
<td v-for="col in columns" :key="col">{{ item[col] }}</td>
</tr>
</tbody>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
脚本部分示例:
export default {
data() {
return {
data: [], // 全部数据
columns: [], // 表头列名
currentPage: 1,
pageSize: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.data.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
使用第三方分页组件
Element UI和Ant Design Vue等UI库提供了现成的分页组件,可以简化实现过程。

Element UI示例:
<template>
<el-table :data="paginatedData">
<el-table-column v-for="col in columns" :key="col" :prop="col" :label="col"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="data.length">
</el-pagination>
</template>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.currentPage = val
}
}
}
</script>
服务器端分页实现
当数据量很大时,应该采用服务器端分页,只请求当前页的数据。

Axios请求示例:
export default {
methods: {
fetchData(page = 1) {
axios.get('/api/data', {
params: {
page,
size: this.pageSize
}
}).then(response => {
this.data = response.data.items
this.total = response.data.total
})
}
},
created() {
this.fetchData()
}
}
分页功能优化
添加页面大小选择器,允许用户自定义每页显示数量。
<select v-model="pageSize" @change="currentPage = 1">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
分页样式美化
使用CSS为分页控件添加基本样式:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






