vue 分页功能实现
分页功能实现思路
在Vue中实现分页功能通常需要结合后端API或前端数据处理。核心逻辑包括计算总页数、当前页数据切片、页码切换事件处理等。以下是两种常见实现方式:
基于前端数据的分页
适用于数据量较小、完全在前端处理的场景。
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span v-for="page in totalPages" :key="page">
<button @click="goToPage(page)" :class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 假设这是全部数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
},
goToPage(page) {
this.currentPage = page
}
}
}
</script>
基于API的分页实现
适用于大数据量场景,需要后端配合返回分页数据。
<template>
<!-- 同上模板结构 -->
</template>
<script>
export default {
data() {
return {
paginatedData: [],
currentPage: 1,
totalItems: 0,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.paginatedData = res.data.items
this.totalItems = res.data.total
},
// 分页方法同上
},
created() {
this.fetchData()
},
watch: {
currentPage() {
this.fetchData()
}
}
}
</script>
使用第三方组件库
常见UI库如Element UI、Ant Design Vue等已封装分页组件:

<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</template>
样式优化建议
- 添加加载状态指示器
- 页码过多时可添加省略号或输入跳转
- 移动端适配时可调整页码显示数量
- 当前页高亮显示
性能注意事项
- 大数据量时务必使用后端分页
- 可添加防抖处理频繁页码切换
- 考虑缓存已加载的页码数据
- 分页参数可保存到URL或Vuex中保持状态持久化






