vue如何实现列表分页
Vue实现列表分页的方法
使用计算属性分页
通过计算属性对数据进行切片处理,结合页码和每页数量实现分页。
data() {
return {
items: [], // 原始数据
currentPage: 1,
perPage: 10
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.perPage
const end = start + this.perPage
return this.items.slice(start, end)
},
totalPages() {
return Math.ceil(this.items.length / this.perPage)
}
}
使用第三方库
可以集成专门的分页组件库如vue-paginate或element-ui的分页组件。

安装vue-paginate:
npm install vue-paginate
基本用法:

import VuePaginate from 'vue-paginate'
Vue.use(VuePaginate)
// 模板中使用
<template>
<paginate
:page-count="totalPages"
:click-handler="changePage"
:container-class="'pagination'"
/>
</template>
服务器端分页
当数据量很大时,建议使用服务器端分页,通过API传递页码和每页数量参数。
methods: {
fetchData(page = 1) {
axios.get(`/api/items?page=${page}&per_page=${this.perPage}`)
.then(response => {
this.items = response.data.items
this.totalPages = response.data.total_pages
})
},
changePage(pageNum) {
this.currentPage = pageNum
this.fetchData(pageNum)
}
}
完整组件示例
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
currentPage: 1,
perPage: 10
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.perPage
const end = start + this.perPage
return this.items.slice(start, end)
},
totalPages() {
return Math.ceil(this.items.length / this.perPage)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
},
created() {
// 获取初始数据
this.items = /* 获取数据逻辑 */;
}
}
</script>
样式处理
可以为分页组件添加CSS样式增强用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






