vue分页插件实现
Vue 分页插件实现方法
使用现有插件(如 vuejs-paginate)
安装插件:
npm install vuejs-paginate --save
注册组件:
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'"
/>
数据绑定与方法:
data() {
return {
currentPage: 1,
itemsPerPage: 10,
totalItems: 100
};
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage);
}
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum;
// 加载对应页数据
}
}
自定义分页组件
创建 Pagination.vue 组件:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>Previous</button>
<span
v-for="page in pages"
:key="page"
@click="goToPage(page)"
:class="{ active: page === currentPage }"
>{{ page }}</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>Next</button>
</div>
</template>
组件逻辑:
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);
}
}
样式示例:
.pagination {
display: flex;
gap: 5px;
}
.pagination span {
cursor: pointer;
padding: 5px 10px;
}
.pagination span.active {
font-weight: bold;
color: blue;
}
与表格数据结合
分页数据处理:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.tableData.slice(start, end);
}
}
高级功能扩展
添加跳转输入框:
<input
type="number"
v-model.number="inputPage"
@keyup.enter="jumpToPage"
min="1"
:max="totalPages"
/>
<button @click="jumpToPage">Go</button>
对应方法:

data() {
return {
inputPage: null
};
},
methods: {
jumpToPage() {
if (this.inputPage >= 1 && this.inputPage <= this.totalPages) {
this.$emit('page-changed', this.inputPage);
}
}
}
注意事项
- 分页组件应尽量保持无状态,通过 props 接收当前页码和总页数
- 使用
v-if或v-show控制分页组件显示条件 - 移动端适配可考虑简化分页按钮数量
- 大型数据集建议配合后端分页实现






