微信小程式scroll-view的例項
阿新 • • 發佈:2018-12-20
近來團隊讓寫一個小程式專案,在寫某個模組首頁列表時,打算採用分頁方式請求後臺,下拉載入更多。
用到官方的一個關鍵標籤 scroll-view。
程式碼如下:
一.在wxml檔案中:
<view class='tipsbar'>共有{{total}}個待簽收批次</view> <view class="navigator-box"> <scroll-view scroll-y="true" bindscrolltolower="scrollLower"> <navigator wx:for="{{batchList}}" class="navigator" bindtap='clickDetails' data-obj="{{item}}"> <view class="list-name"><text class='link'>{{item.sn}}</text> </view> <view class="list-info"> <text>{{item.purchaseBatch.sn}}</text> <text decode="{{true}}" space="{{true}}"> </text>/ <text decode="{{true}}" space="{{true}}"> </text> <text>{{item.purchaseBatch.name}}</text> </view> <view class='list-detail'> <text>到貨區域:<text class='text-inverse'>{{item.purchaseBatch.place.sn}}</text></text> <text>到貨數量:<text class='text-inverse'>{{item.allArrivalItemCount}}</text></text> </view> </navigator> <loading hidden="{{!loading}}">正在載入更多...</loading> <view class="loadingComplete" hidden="{{!loadingComplete}}">已載入全部</view> </scroll-view> </view>
二.在js檔案中:
var util=require('../../utils/util.js') Page({ /** * 頁面的初始資料 */ data: { batchList:[], total:0, pageNum:1, pageSize:8, isNullList:true, loading:true, loadingComplete:false }, /** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) { }, /** * 生命週期函式--監聽頁面初次渲染完成 */ onReady: function () { }, /** * 生命週期函式--監聽頁面顯示 */ onShow: function () { this.setData({ batchList: [], pageNum: 1, isNullList: true, loading: true, loadingComplete: false }); this.getBatchList(); }, /** * 生命週期函式--監聽頁面隱藏 */ onHide: function () { }, /** * 生命週期函式--監聽頁面解除安裝 */ onUnload: function () { }, /** * 頁面相關事件處理函式--監聽使用者下拉動作 */ onPullDownRefresh: function () { }, /** * 頁面上拉觸底事件的處理函式 */ onReachBottom: function () { }, /** * 使用者點選右上角分享 */ onShareAppMessage: function () { }, /** * 請求後臺獲取資料 */ getBatchList: function () { var that=this; var option = {url: '/api/cmdb/arrival/list', data: { pageNum: that.data.pageNum, pageSize: that.data.pageSize} } util.request(option).then(function(res){ if(res.data.data.pageData.length>0){ var list=[]; that.data.isNullList ?list = res.data.data.pageData : list=that.data.batchList.concat(res.data.data.pageData); that.setData({ total: res.data.data.totalRecords, batchList:list, loading:false }); }else{ that.setData({ loadingComplete:true, loading:false }); } }) }, /** * 上拉載入 */ scrollLower:function(){ var that=this; if (that.data.loading==false && that.data.loadingComplete==false){ that.setData({ pageNum:that.data.pageNum+1, isNullList:false, loading:true }); that.getBatchList(); } },
三.在wxss檔案中
page{
display: flex;
flex-direction: column;
height: 100%;
}
.navigator-box {
flex: auto;
position:relative;
}
.navigator-box scroll-view{
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
}
.loadingComplete{
padding: 10rpx;
text-align: center;
}
還有以下兩點要說明一下:
- css樣式的設定,在這裡採用了flex的方式,似乎scroll-view標籤正如網上其他文章介紹的那樣,有個坑,當height沒設定好時,無法觸發上拉載入。所以在這裡直接避免那個問題,採用flex和定位。
- 關於上拉載入時的提醒,採用官方的<loading>標籤,不需要自己再做一個了。它和載入完成時的提醒採用標誌位的思想來區分。具體邏輯可以看js中的程式碼。