vue 实现数据分页
数据分页的实现方法
在Vue中实现数据分页通常需要结合前端分页和后端分页两种方式。前端分页适合数据量较小的情况,后端分页适合大数据量场景。
前端分页实现
前端分页是将所有数据一次性加载到前端,通过计算实现分页效果。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
allItems: [] // 这里存放所有数据
}
},
computed: {
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
},
created() {
// 这里可以调用API获取所有数据
// this.fetchAllData()
}
}
</script>
后端分页实现
后端分页通过API请求实现,每次只获取当前页的数据。

<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [],
totalItems: 0
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
limit: this.itemsPerPage
}
// 调用API获取分页数据
// axios.get('/api/items', { params })
// .then(response => {
// this.items = response.data.items
// this.totalItems = response.data.total
// })
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.fetchData()
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.fetchData()
}
}
},
created() {
this.fetchData()
}
}
</script>
使用第三方组件
可以使用现成的分页组件如Element UI的Pagination:
<template>
<div>
<el-table :data="items">
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [],
totalItems: 0
}
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
limit: this.itemsPerPage
}
// API调用
},
handleCurrentChange(page) {
this.currentPage = page
this.fetchData()
}
},
created() {
this.fetchData()
}
}
</script>
分页优化技巧
对于大数据量场景,建议采用后端分页方式,减少前端性能压力。

在分页请求时可以添加加载状态提示,提升用户体验。
考虑实现页面大小切换功能,让用户可以选择每页显示的数据量。
对于表格分页,可以添加排序功能,与分页结合使用。





