vue如何实现分页
Vue 实现分页的方法
使用第三方库(如 Element UI、Vant 等)
许多 UI 框架提供了现成的分页组件,可以直接使用。以 Element UI 为例:
安装 Element UI:
npm install element-ui
在 Vue 组件中使用:

<template>
<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="total"
@current-change="handleCurrentChange"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据 currentPage 和 pageSize 获取数据
}
}
}
</script>
自定义分页组件
如果需要更灵活的控制,可以自定义分页组件:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>
上一页
</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
}
}
}
</script>
结合后端 API 实现分页
通常分页需要与后端 API 配合:

<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
items: []
}
},
mounted() {
this.fetchData()
},
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.items = response.data.items
this.total = response.data.total
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
}
</script>
前端本地分页
如果数据量不大,可以在前端进行分页:
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
allItems: [],
displayedItems: []
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.allItems.length / this.pageSize)
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
}
}
}
</script>
分页样式优化
可以添加样式增强用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
以上方法可以根据项目需求选择使用,第三方库适合快速开发,自定义组件提供更大灵活性,后端分页适合大数据量场景,前端分页适合小数据量情况。






