
開發小程式分頁功能遇到的坑
微信小程式開發中list串列經常要進行分頁處理,踩坑在所難免,
app.json
"enablePullDownRefresh": true
wxml
<view wx:if="{{showEmpty}}">暫無資料</view>
<scroll-view wx:else scroll-y="true" style="height: 100vh" bindscrolltolower="getMoreList">
<view wx:for="{{list}}" wx:key="index">
// ...內容省略
</view>
</scroll-view>
js
const httpUtil = require('../../../utils/httpUtil.js') // 網路請求工具
const api = require('../../../config/api.js') // api檔案
const size = 10; // 每頁資料量
let current = 1; // 當前頁數
let maxPage = 0; // 最大頁數
Page({
data: {
showEmpty: false,
list: []
},
getList() {
const that = this
httpUtil.getRequest(api.getRecordList, {
current,
size
}, (res) => {
const { records = [], pages } = res;
if (current === 1 && records.length === 0) {
that.setData({
showEmpty: true
})
return
}
let { list } = that.data
maxPage = pages;
let recordList = current === 1 ? list : list.concat(records)
that.setData({
list: recordList,
showEmpty: false
})
}, () => {})
},
getMoreList() {
if (current < maxPage) {
current++;
this.getList();
}
},
/**
* 生命周期函式--監聽頁面加載
*/
onl oad: function (options) {
this.getList()
},
/**
* 頁面相關事件處理函式--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
current = 1;
this.getList();
wx.stopPullDownRefresh();
}
})
看似沒問題的分頁邏輯代碼,存在3個大坑
坑一:頁面回傳后,再次進入list頁面,curent maxPage變數不會初始化重置
解決方法1:
onLoad: function (options) {
current = 1;
maxPage = 0;
this.getList()
},
解決方法2:
Page({
data: {
showEmpty: false,
list: []
},
current: 1, // 運用時this.current
maxPage: 0 // 運用時this.maxPage
})
坑二:page自帶的onPullDownRefresh與scroll-view的重繪功能沖突,將會失效
解決方法:(view替換scroll-view)
<view wx:if="{{showEmpty}}">暫無資料</view>
<view wx:else style="height: 100vh">
<view wx:for="{{list}}" wx:key="index">
// ...內容省略
</view>
</view>
js:
/**
* 頁面上拉觸底事件的處理函式
*/
onReachBottom: function () {
if (current < maxPage) {
current++;
this.getDeviceList();
}
},
坑三:加載頁面資料,size值偏小,永遠無法觸底
如果一個頁面,每條item高度較小,第一頁加載完后無法撐滿整個頁面的高度,這樣將永遠無法觸發頁面底部加載更多的方法

解決方法:增加每頁的加載量,size增大
const size = 15; // 每頁資料量
關注公眾號: 頁面仔小楊 【實戰干貨、原創分享】
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/235426.html
標籤:其他
