vue实现分页效果
使用 Element UI 的 Pagination 组件
Element UI 提供了一个现成的 Pagination 组件,可以快速实现分页效果。安装 Element UI 后,在组件中引入并使用。
<template>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据 currentPage 和 pageSize 获取数据
}
}
}
</script>
自定义分页组件
如果需要自定义分页样式,可以手动实现一个分页组件。创建一个 Pagination.vue 文件,定义分页逻辑和样式。
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
: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)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
结合后端 API 实现分页
分页通常需要与后端 API 配合,传递当前页码和每页数量,获取对应的数据。
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.pageSize
}
})
this.items = response.data.items
this.total = response.data.total
}
}
使用 Vuex 管理分页状态
在大型应用中,可以使用 Vuex 集中管理分页状态,便于多个组件共享和同步。
// store.js
export default new Vuex.Store({
state: {
pagination: {
currentPage: 1,
pageSize: 10,
total: 0
}
},
mutations: {
setCurrentPage(state, page) {
state.pagination.currentPage = page
},
setPageSize(state, size) {
state.pagination.pageSize = size
},
setTotal(state, total) {
state.pagination.total = total
}
}
})
分页与表格结合
分页常与表格一起使用,通过计算属性实现表格数据的分页显示。
<template>
<div>
<table>
<tr v-for="item in paginatedItems" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<pagination
:total-items="items.length"
:items-per-page="pageSize"
:current-page="currentPage"
@page-changed="changePage">
</pagination>
</div>
</template>
<script>
export default {
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.items.slice(start, end)
}
}
}
</script>






