一,遇到問題
在開發微信小程序:【澳買】這個項目的時候,當用戶按關鍵詞搜索某個產品的時候,如果搜索結果比較多,
比如100條或者更多,我們不可能也不應該在手機上都給用戶顯示出來的,這個時候怎么辦呢?
二,解決思路
方案很簡單,肯定是要用到翻頁的功能了,那問題就轉化為在微信小程序里面我們如何實現翻頁呢?
首先,我們要充分利用手機手指的翻頁功能,比如用戶下滑翻到屏幕底部,我們開始加載一下屏的數據,直到
加載完所有的搜索結果,我們再在手機屏幕底部提示用戶,已經加載完全部產品數據。
三,技術實施
你等的干貨來了,請接好:
1. 微信小程序的已經提供了現成的判斷是否翻到頁面底部回調函數:
onReachBottom
我們只需要把我們的操作邏輯代碼加入這個回調函數即可:
1 /** 2 * Called when page reach bottom 3 */ 4 onReachBottom: function () { 5 6 if ( self.data.nomoreData ) { 7 this.setData({ 8 showloading: true, 9 loadingMoreTips: '沒有更多商品了' 10 }); 11 return; 12 } 13 14 this.setData({ 15 showloading: true, 16 }); 17 18 19 db.collection('pinfo') 20 .where({ 21 cname: db.RegExp({ 22 regexp: this.data.searchname, 23 options: 'i' 24 }) 25 }) 26 .field({ 27 _id: true, 28 images: true, 29 cname: true, 30 bname: true, 31 }).skip(self.data.totalItems) 32 .limit(MAX_PAGE_LIMIT) 33 .get({ 34 success: function (res) { 35 self.setData({ 36 showloading: false, 37 }); 38 if (res.data.length > 0) { 39 self.data.totalItems += res.data.length; 40 let pitems = self.data.items; 41 for (let i in res.data) { 42 let pdata = res.data[i]; 43 pitems.push({ 44 'id': pdata['_id'], 45 'barcode': pdata['_id'], 46 'image': app.globalData.pimage_root + pdata['images'][0], 47 'name': pdata['cname'], 48 'brand_name': pdata['bname'] 49 }); 50 } 51 52 //console.log('update items'); 53 self.setData({ 54 items: pitems 55 }); 56 57 } else { 58 self.data.nomoreData = true; 59 self.setData({ 60 showloading: false, 61 }); 62 } 63 }, 64 fail: function (error) { 65 self.setData({ 66 showloading: false, 67 }); 68 } 69 }); 70 71 },
大家注意到沒有,上面的處理邏輯里面用了一個非常重要的變量:
self.data.nomoreData // 用來標識數據是否全部加載完畢
初始化的時候 改變量我們賦值是false,在第58行的時候,會判斷如果沒有數據了,就設置為true了。
page data的 初始化代碼如下:
1 /** 2 * Page initial data 3 */ 4 data: { 5 showloading: false, 6 nomoreData: false, 7 searchname: '', 8 totalItems: 0, 9 items: [], 10 loadingResult: '努力加載...', 11 loadingMoreTips: '玩命加載中...' 12 },