vue.js 实现分页
Vue.js 实现分页的方法
使用计算属性分页
通过计算属性对数据进行分页处理,结合 v-for 渲染分页数据。定义一个 currentPage 变量和 itemsPerPage 变量控制当前页和每页显示数量。
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);
}
}
模板中使用 paginatedItems 渲染当前页数据,并通过按钮切换页码:
<ul>
<li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
<button @click="currentPage++" :disabled="currentPage === totalPages">下一页</button>
使用第三方库
借助 vue-paginate 或 v-pagination 等第三方库快速实现分页。以 vue-paginate 为例:
安装库:

npm install vue-paginate
在组件中注册并使用:
import VuePaginate from 'vue-paginate';
Vue.use(VuePaginate);
模板中直接使用组件:

<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'上一页'"
:next-text="'下一页'"
></paginate>
后端分页结合 API
对于大数据量,建议通过后端分页。前端传递页码和每页数量参数,后端返回对应数据。
methods: {
fetchData(page) {
axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`)
.then(response => {
this.items = response.data.items;
this.totalPages = response.data.totalPages;
});
},
changePage(page) {
this.currentPage = page;
this.fetchData(page);
}
}
分页样式优化
通过 CSS 自定义分页样式,例如高亮当前页:
.pagination {
display: flex;
list-style: none;
}
.pagination li {
margin: 0 5px;
cursor: pointer;
}
.pagination li.active {
font-weight: bold;
color: blue;
}
在模板中绑定 active-class:
<paginate
:page-count="totalPages"
:container-class="'pagination'"
:page-class="'page-item'"
:active-class="'active'"
></paginate>
以上方法可根据项目需求选择或组合使用。计算属性分页适合前端数据量较小的情况,后端分页适合大数据量场景,第三方库能快速实现标准化分页功能。






