加載更多,其實就是再次向接口發送請求,把返回的數據,追加到渲染頁面的數組里的過程,具體實現實例如下:
demo.js
// pages/project/project.js const app = getApp() Page({ /** * 頁面的初始數據 */ data: { //每頁顯示的行數: pagesize: 7, //頁碼(從1開始): p: 1, //排序方式: paixu: 'viewcount', //升序或降序: order: 'desc', //用於標識是否還有更多的狀態 state: 1, //用於渲染頁面的數組 arrayProject:[], //用於數組的追加和暫存 allProject:[], }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function (options) { var mythis = this; getproinfo( this.data.pagesize, this.data.p,mythis) }, /** * 點擊加載更多時觸發 */ loadMore:function(){ var mythis = this; wx.showLoading({ title: '玩命加載中...', }); mythis.data.p = mythis.data.p + 1; getproinfo(this.data.pagesize, this.data.p,mythis); wx.hideLoading(); }, /** * 頁面上拉觸底事件的處理函數,與點擊加載更多做同樣的操作 */ onReachBottom: function () { var mythis = this; wx.showLoading({ title: '玩命加載中...', }); mythis.data.p = mythis.data.p + 1; getproinfo(this.data.pagesize, this.data.p,mythis); wx.hideLoading(); }, }) /** * 獲取項目列表 */ function getproinfo(pagesize, p, mythis){ wx.request({ url: app.globalData.host + 'index.php/Ho/getproinfo', method: 'post', data: { pagesize: pagesize, p:p }, header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) {
//如果搜出來的結果<1 就說明后面已經沒數據可加載了,所以將state設為0 if (res.data.rows.length<1) mythis.setData({ state: 0 }); else{ var state1 = 1;
//如果有數據,但小於每次期望加載的數據量(pagesize),將state設為0,表示后面已沒有數據可加載 if (res.data.rows.length < mythis.data.pagesize) var state1 = 0; //循環將結果集追加到數組后面 for (var i = 0; i < res.data.rows.length; i++) { mythis.data.allProject.push(res.data.rows[i]); } mythis.setData({ arrayProject: mythis.data.allProject, state: state1 }); } console.log(mythis.data.arrayProject) }, fail: function (res) { console.log(res); } }); }
demo.html
<view class='projectlist' > <view class='project' wx:for="{{arrayProject}}" wx:for-item="itemProjec" wx:key="id" data-datas="{{itemProjec}}" bindtap='projectDetail'> <view class='projectText'> {{itemProjec.gongchengmingcheng}} </view> <view class='projectleibie label'> {{arrayCategory[itemProjec.leixing].name}} </view> <view class='projectjiesuan label'> {{arraySchedule[itemProjec.jieduan].name}} </view> <view class='projectTime'> {{itemProjec.faburiqi}} </view> </view>
<!--
實現點擊“加載更多”時進行加載
<view class='remind' bindtap='loadMore' wx:if="{{state==0}}"><view><<加載更多<<</view></view>
<view class='remind' wx:elif="{{state==0}}"><view>沒有更多了</view></view>
-->
//實現屏幕上拉加載更多 <view class='remind' wx:if="{{state==0}}"><view>沒有更多了</view></view> </view>