在使用uniapp寫小程序項目時,需要在頁面展示列表,列表需要分頁滾動加載;一般情況下整個頁面滾動可以直接在onReachBottom中直接實現,但是需求不能滾動整個頁面;所以需要采用scroll-view控件進行操作;
首先,先看下頁面基本的布局情況:
<template> <view style="position: fixed;width: 100%;"> ......
先把整個頁面設置為固定大小,這樣就不會影響下邊的scroll-view滾動
<view> <scroll-view :style="'height:'+ height" scroll-y lower-threshold="30" @scrolltolower="LoadMoreCustomers"> <view v-for="(item,index) in customerList" :key="index" class="touch-item" :data-index="index" > <view class="itemcontent"> ...... </view> </view> </scroll-view> <view v-if="loading&&PageIndex>0" style="position:absolute;bottom:0;width:100%;display:flex;align-items:center;justify-content:center;"> <view class="weui-loading"></view> <view class="weui-loadmore__tips">正在加載</view> </view> </view>
在以上代碼中,主要有幾個點:
1、height :scroll-view控件的style屬性必須要設置一個固定的高度,這個高度確定了滾動條控件的大小;當內容高度大於滾動條時才會觸發滾動效果;
2、scrolltolower 事件:當滾動條滾動到最底部或最右側時觸發;
3、scroll-y 屬性:表示允許滾動條垂直滾動;
4、lower-threshold="30":表示在滾動條距離最下方30像素時開始加載新數據;
5、在scroll-view下方的view是一個正在加載的區域;具體的樣式是在weui.css中,網上可以很多地方可以下載;
繼續,下邊是vue代碼部分
export default { data() { return { height: '0px', PageIndex: 0, PageSize: 20, HasMore: true, loading: false, customerList: [] } }, onShow() { let height = uni.getSystemInfoSync().windowHeight; this.height = (height - 100) + 'px'; this.PageIndex = 0; this.HasMore = true; this.customerList = []; this.LoadCustomerList(); }, methods: { LoadCustomerList() { ...... }, LoadMoreCustomers() { if (this.HasMore && !this.loading) { this.LoadCustomerList(); } } } }
這段代碼中:
1、在onshow中將height計算出來,使用屏幕高度減去頁面其他控件占用高度得出scroll-view需要的高度
2、默認每頁加載20條數據;
3、使用HasMore記錄是否還有新的頁面
4、LoadCustomerList這個方法是加載數據的方法,每次讀取一頁數據,PageIndex就增加對應值;如果讀取的數據小於20條就表示沒有新的數據了,HasMore即設置為false;
5、LoadMoreCustomers中首先判斷是否有新數據並且沒有正在加載數據,然后再調用方法加載新數據;