vue分页插件实现
Vue 分页插件实现方法
使用第三方库(推荐)
安装 vuejs-paginate 或 v-pagination 等成熟分页库:
npm install vuejs-paginate
注册组件:
import Vue from 'vue'
import VuePaginate from 'vuejs-paginate'
Vue.component('paginate', VuePaginate)
模板中使用:

<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'Prev'"
:next-text="'Next'"
:container-class="'pagination'"
/>
自定义分页组件
创建 Pagination.vue 组件:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span v-for="page in pages" :key="page">
<button
@click="goToPage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
},
goToPage(page) {
this.$emit('page-changed', page)
}
}
}
</script>
与数据结合使用
父组件中实现分页逻辑:

data() {
return {
currentPage: 1,
itemsPerPage: 10,
allItems: [...] // 你的完整数据
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
}
}
样式定制
添加基础CSS样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级功能扩展
对于大型数据集:
- 添加页面跳转输入框
- 实现动态页码范围计算(只显示当前页附近的页码)
- 添加每页条数选择器
- 结合路由实现URL同步
// 动态页码计算示例
pages() {
const range = []
const maxVisible = 5
let start = Math.max(1, this.currentPage - Math.floor(maxVisible/2))
let end = Math.min(this.totalPages, start + maxVisible - 1)
if (end - start + 1 < maxVisible) {
start = Math.max(1, end - maxVisible + 1)
}
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}






