分页用vue实现
实现分页的基本思路
在Vue中实现分页功能,通常需要以下几个核心部分:数据列表、当前页码、每页显示数量、总页数计算、页码切换逻辑。以下是一个完整的实现方案。
分页组件代码示例
<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">上一页</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">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
dataList: [], // 原始数据
currentPage: 1, // 当前页码
itemsPerPage: 10 // 每页显示数量
}
},
computed: {
totalPages() {
return Math.ceil(this.dataList.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.dataList.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
goToPage(page) {
this.currentPage = page
}
},
created() {
// 模拟数据获取
for (let i = 1; i <= 100; i++) {
this.dataList.push({ id: i, name: `项目 ${i}` })
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
关键实现细节
数据分片计算
通过计算属性paginatedData实现当前页数据的切片显示:
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.dataList.slice(start, end)
}
总页数计算 基于数据总量和每页显示数量计算总页数:

totalPages() {
return Math.ceil(this.dataList.length / this.itemsPerPage)
}
页码切换控制 提供三个基本方法处理页码切换:
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
goToPage(page) {
this.currentPage = page
}
进阶优化建议
分页组件封装 将分页逻辑抽离为独立组件,通过props接收数据:

<pagination
:total-items="dataList.length"
:items-per-page="itemsPerPage"
:current-page="currentPage"
@page-changed="handlePageChange"
/>
异步数据加载 结合API请求实现服务端分页:
async fetchData(page) {
const response = await axios.get(`/api/items?page=${page}`)
this.dataList = response.data.items
this.totalItems = response.data.total
}
显示优化 添加页码范围限制,避免显示过多页码按钮:
visiblePages() {
const range = 2
const start = Math.max(1, this.currentPage - range)
const end = Math.min(this.totalPages, this.currentPage + range)
return Array.from({ length: end - start + 1 }, (_, i) => start + i)
}
以上实现方案涵盖了Vue分页的核心功能,可根据实际需求进行扩展和调整。






