vue实现table表格分页
实现基础表格分页
在Vue中实现表格分页需要结合el-table和el-pagination组件(Element UI为例)。以下是一个基础实现方案:
<template>
<div>
<el-table :data="currentPageData" border>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[5, 10, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [], // 全部数据
currentPageData: [], // 当前页数据
currentPage: 1,
pageSize: 5,
total: 0
}
},
methods: {
fetchData() {
// 模拟API请求
this.tableData = Array.from({length: 23}, (_, i) => ({
name: `用户${i+1}`,
age: Math.floor(Math.random() * 30) + 20
}))
this.total = this.tableData.length
this.updatePageData()
},
updatePageData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
this.currentPageData = this.tableData.slice(start, end)
},
handleSizeChange(val) {
this.pageSize = val
this.updatePageData()
},
handleCurrentChange(val) {
this.currentPage = val
this.updatePageData()
}
},
created() {
this.fetchData()
}
}
</script>
服务器端分页实现
当数据量较大时,建议采用服务器端分页:

methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.currentPageData = res.data.list
this.total = res.data.total
},
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
自定义分页样式
可以通过CSS自定义分页组件样式:

.el-pagination {
margin-top: 20px;
text-align: center;
}
.el-pagination.is-background .el-pager li:not(.disabled).active {
background-color: #409EFF;
color: #fff;
}
分页与表格联动优化
添加加载状态提升用户体验:
<el-table v-loading="loading" :data="currentPageData">
<!-- 表格列定义 -->
</el-table>
<script>
export default {
data() {
return {
loading: false
}
},
methods: {
async fetchData() {
this.loading = true
try {
// 数据获取逻辑
} finally {
this.loading = false
}
}
}
}
</script>
分页缓存策略
对于频繁访问的页面,可以添加缓存机制:
const pageCache = {}
methods: {
async fetchData() {
const cacheKey = `${this.currentPage}-${this.pageSize}`
if (pageCache[cacheKey]) {
this.currentPageData = pageCache[cacheKey]
return
}
const res = await axios.get('/api/data', {
params: { page: this.currentPage, size: this.pageSize }
})
pageCache[cacheKey] = res.data.list
this.currentPageData = res.data.list
this.total = res.data.total
}
}
以上实现方案可以根据具体项目需求进行调整,如添加排序功能、筛选条件等与分页的联动处理。






