vue实现移动端分页
Vue实现移动端分页的方法
使用第三方库实现分页
移动端分页可以使用第三方库如vant或mint-ui,这些库提供了现成的分页组件,适合快速开发。
安装vant库:
npm install vant
引入分页组件:
import { Pagination } from 'vant';
Vue.use(Pagination);
在模板中使用:
<van-pagination
v-model="currentPage"
:total-items="total"
:items-per-page="pageSize"
@change="handlePageChange"
/>
自定义分页组件
如果需要更灵活的分页逻辑,可以自定义分页组件。定义一个Pagination组件,包含页码按钮和上一页/下一页按钮。
模板部分:

<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in pages" :key="page" @click="goToPage(page)" :class="{ active: currentPage === page }">
{{ page }}
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
脚本部分:
export default {
props: {
total: Number,
pageSize: Number,
currentPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.total / this.pageSize);
},
pages() {
const range = [];
for (let i = 1; i <= this.totalPages; i++) {
range.push(i);
}
return range;
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.$emit('page-changed', this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.$emit('page-changed', this.currentPage + 1);
}
},
goToPage(page) {
this.$emit('page-changed', page);
}
}
};
结合后端API实现分页
移动端分页通常需要与后端API交互,通过传递页码和每页大小参数获取数据。
示例代码:
methods: {
fetchData(page) {
axios.get('/api/data', {
params: {
page: page,
size: this.pageSize
}
}).then(response => {
this.dataList = response.data.list;
this.total = response.data.total;
});
},
handlePageChange(page) {
this.fetchData(page);
}
}
无限滚动分页
移动端常见无限滚动分页,滚动到底部时自动加载下一页数据。

使用v-infinite-scroll指令:
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<div v-for="item in list" :key="item.id">{{ item.name }}</div>
</div>
脚本部分:
data() {
return {
list: [],
page: 1,
busy: false
};
},
methods: {
loadMore() {
this.busy = true;
axios.get('/api/data', {
params: {
page: this.page,
size: 10
}
}).then(response => {
this.list = this.list.concat(response.data.list);
this.page++;
this.busy = false;
});
}
}
样式优化
移动端分页组件需要适配小屏幕,样式应简洁且易于点击。
CSS示例:
.pagination {
display: flex;
justify-content: center;
padding: 10px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination span {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination .active {
font-weight: bold;
color: #1989fa;
}
通过以上方法,可以在Vue中实现适合移动端的分页功能,根据需求选择合适的方式。






