Vue分页功能实现步骤
实现基础分页功能
在Vue中实现分页功能需要结合数据分割和页面交互。以下是一个基础实现方案:
-
准备分页数据 定义数据列表和分页相关变量:
data() { return { items: [], // 原始数据列表 currentPage: 1, // 当前页码 itemsPerPage: 10 // 每页显示数量 } } -
计算分页数据 使用计算属性实现数据分片:
computed: { paginatedItems() { const start = (this.currentPage - 1) * this.itemsPerPage const end = start + this.itemsPerPage return this.items.slice(start, end) }, totalPages() { return Math.ceil(this.items.length / this.itemsPerPage) } }
添加分页导航组件
创建分页导航界面控制页码切换:
<template>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }">
{{ page }}
</span>
<button
@click="currentPage++"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
优化分页显示
添加页码范围限制,避免显示过多页码:

computed: {
visiblePages() {
const range = 2 // 显示前后范围
let start = Math.max(1, this.currentPage - range)
let end = Math.min(this.totalPages, this.currentPage + range)
if (this.currentPage - start < range) {
end = Math.min(this.totalPages, start + range * 2)
}
if (end - this.currentPage < range) {
start = Math.max(1, end - range * 2)
}
return Array.from({length: end - start + 1}, (_, i) => start + i)
}
}
处理异步数据
当数据来自API请求时的处理方式:
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total // 从服务器获取总条目数
}
},
watch: {
currentPage() {
this.fetchData()
}
}
使用第三方分页组件
推荐使用成熟的分页组件如vue-paginate:
-
安装组件

npm install vue-paginate -
基础使用
import VuePaginate from 'vue-paginate' Vue.use(VuePaginate)
// 模板中使用
```样式优化建议
为分页组件添加基础样式:
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.page-item {
margin: 0 5px;
cursor: pointer;
padding: 5px 10px;
border: 1px solid #ddd;
}
.page-item.active {
background-color: #42b983;
color: white;
border-color: #42b983;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






