小程序分页通常是在列表展示场景中用于管理数据量较大的情况,避免一次性加载所有数据导致页面性能下降。微信小程序的分页功能一般通过wx:for 和 wx:offset 或者 scroll-view 组件配合 bindscrolltolower 和 bindscrolltopchange 事件来实现。
使用 list 组件时,可以结合 wx:for-item="item"和 wx:offset="index * itemHeight" 来遍历数据并设置偏移量,让用户滚动到下一页时加载更多数据。
Html
<view class="list">
<list wx:for="{{items}}" wx:for-item="item" wx:offset="{{index * itemHeight}}">
<!-- 显示每个列表项 -->
</list>
</view>
如果使用的是 scroll-view 组件,可以监听滚动到底部(bindscrolltolower) 和滚动位置改变(bindscrolltopchange) 的事件,在满足条件时发送请求获取下一页的数据,并更新界面。
Javascript
Page({
data: {
items: [],
pageSize: 10,
currentPage: 1,
},
onLoad() {
this.getData();
},
bindScrollToLower(e) {
if (this.data.scrollTop + this.data.offsetHeight === this.data.contentHeight) {
// 加载更多数据
this.loadMoreData();
}
},
loadMoreData() {
const newPage = this.data.currentPage + 1;
this.setData({ currentPage: newPage });
// 发送请求...
},
})