vue实现分页效果
使用Element UI实现分页
安装Element UI库后,可以直接使用el-pagination组件。需要在Vue项目中引入并注册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() {
// 获取分页数据逻辑
}
}
}
</script>
自定义分页组件实现
如果需要完全自定义分页组件,可以创建一个独立的Pagination组件。
<template>
<div class="pagination">
<button
:disabled="currentPage === 1"
@click="changePage(currentPage - 1)">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
:disabled="currentPage === totalPages"
@click="changePage(currentPage + 1)">
下一页
</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: #409EFF;
color: white;
}
</style>
与后端API交互
实现分页通常需要与后端API配合,传递分页参数并接收分页数据。
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.dataList = response.data.items
this.total = response.data.total
} catch (error) {
console.error('获取数据失败:', error)
}
}
}
使用Vuex管理分页状态
在大型应用中,可以使用Vuex集中管理分页状态。
// store/modules/pagination.js
const state = {
currentPage: 1,
pageSize: 10,
total: 0
}
const mutations = {
SET_PAGE(state, page) {
state.currentPage = page
},
SET_PAGE_SIZE(state, size) {
state.pageSize = size
},
SET_TOTAL(state, total) {
state.total = total
}
}
const actions = {
updatePage({ commit }, page) {
commit('SET_PAGE', page)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
响应式分页布局
可以根据屏幕尺寸调整分页显示方式,提升移动端体验。
<template>
<div class="pagination-container">
<div class="pagination-buttons" v-if="!isMobile">
<!-- 桌面端完整分页 -->
</div>
<div class="mobile-pagination" v-else>
<!-- 移动端简化分页 -->
</div>
</div>
</template>
<script>
export default {
computed: {
isMobile() {
return window.innerWidth < 768
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.$forceUpdate()
}
}
}
</script>






