小程序分页通常用于展示大量数据时,通过分页来提高用户体验和性能。以下是一个简单的小程序分页代码示例,使用 `wx.request` 获取数据,并使用 `<block wx:for>` 进行数据渲染。
1. 获取分页数据
首先,我们需要一个后端接口来提供分页数据。假设我们的后端接口是 `/api/data?page=1&size=10`,其中 `page` 是当前页码,`size` 是每页的数据条数。
2. 小程序代码
以下是一个简单的小程序分页代码示例:
<!-- pages/index/index.wxml -->
<view class="container"> <block wx:for="{{data}}" wx:key="id"> <view class="item">{{item.name}}</view> </block> <view class="pagination"> <button bindtap="prevPage" wx:if="{{currentPage > 1}}">上一页</button> <button bindtap="nextPage" wx:if="{{currentPage < totalPages}}">下一页</button> <text>当前页: {{currentPage}}/{{totalPages}}</text> </view> </view>
<!-- pages/index/index.js-->
Page({ data: { data: [], currentPage: 1, totalPages: 0, pageSize: 10, }, // 获取分页数据 getPageData(page) { const url = `/api/data?page=${page}&size=${this.data.pageSize}`; wx.request({ url, method: 'GET', success: (res) => { const { data, totalPages } = res.data; this.setData({ data, totalPages, }); }, fail: (err) => { console.error('请求失败', err); }, }); }, // 上一页 prevPage() { if (this.data.currentPage > 1) { this.setData({ currentPage: this.data.currentPage - 1 }); this.getPageData(this.data.currentPage); } }, // 下一页 nextPage() { if (this.data.currentPage < this.data.totalPages) { this.setData({ currentPage: this.data.currentPage + 1 }); this.getPageData(this.data.currentPage); } }, // 初始化数据 onLoad() { this.getPageData(this.data.currentPage); }, });
3. 样式<!-- pages/index/index.wxss-->
.container { padding: 20px; } .item { padding: 10px; border-bottom: 1px solid #eee; } .pagination { margin-top: 20px; } button { margin-right: 10px; } text { margin-left: 10px; }
4. 注意事项
- 确保后端接口能够正确处理分页请求。
- 根据实际需求调整 `pageSize` 和分页逻辑。
- 在生产环境中,建议添加更多的错误处理和用户体验优化。