vue实现手机分页教程
Vue实现手机分页教程
在Vue中实现手机分页功能,通常需要结合后端API的分页数据和前端UI组件。以下是具体实现方法:
数据准备
确保后端API支持分页参数(如page和pageSize),返回格式应包含当前页数据及总条数:
{
"data": [],
"total": 100
}
基础实现
安装依赖(如需要):
npm install axios
创建分页组件:
<template>
<div class="mobile-pagination">
<ul v-if="total > pageSize">
<li @click="prevPage" :class="{ disabled: currentPage === 1 }">上一页</li>
<li v-for="page in visiblePages"
@click="goToPage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</li>
<li @click="nextPage" :class="{ disabled: currentPage === totalPages }">下一页</li>
</ul>
</div>
</template>
<script>
export default {
props: {
total: Number,
pageSize: { type: Number, default: 10 },
currentPage: { type: Number, default: 1 }
},
computed: {
totalPages() {
return Math.ceil(this.total / this.pageSize)
},
visiblePages() {
const range = 2
let start = Math.max(1, this.currentPage - range)
let end = Math.min(this.totalPages, this.currentPage + range)
return Array.from({ length: end - start + 1 }, (_, i) => start + i)
}
},
methods: {
goToPage(page) {
if (page !== this.currentPage) {
this.$emit('page-change', page)
}
},
prevPage() {
if (this.currentPage > 1) {
this.goToPage(this.currentPage - 1)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.goToPage(this.currentPage + 1)
}
}
}
}
</script>
结合数据加载
在父组件中调用API:
<script>
import axios from 'axios'
export default {
data() {
return {
list: [],
pagination: {
page: 1,
pageSize: 10,
total: 0
}
}
},
methods: {
async fetchData() {
const res = await axios.get('/api/list', {
params: {
page: this.pagination.page,
size: this.pagination.pageSize
}
})
this.list = res.data.data
this.pagination.total = res.data.total
}
},
created() {
this.fetchData()
}
}
</script>
移动端优化技巧
- 使用无限滚动代替传统分页(适合长列表):
<template> <div @scroll="handleScroll" style="overflow-y: auto; height: 100vh"> <!-- 列表内容 --> <div v-if="loading" class="loading">加载中...</div> </div> </template>
vant):<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-list
v-model:loading="loading"
:finished="finished"
@load="onLoad"
>
<!-- 列表内容 -->
</van-list>
</van-pull-refresh>
样式优化
针对移动端的CSS建议:
.mobile-pagination {
display: flex;
justify-content: center;
padding: 10px 0;
}
.mobile-pagination ul {
display: flex;
list-style: none;
padding: 0;
}
.mobile-pagination li {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
border-radius: 3px;
}
.mobile-pagination li.active {
background-color: #42b983;
color: white;
}
.mobile-pagination li.disabled {
opacity: 0.5;
pointer-events: none;
}
注意事项
- 移动端分页按钮不宜过多,建议显示当前页前后各2页
- 添加加载状态提示,提升用户体验
- 考虑使用第三方UI库(如Vant、Mint UI)的现成分页组件
- 对于超长列表,优先考虑无限滚动方案







