uniapp 实现页面列表分页加载

在使用uniapp写小程序项目时,需要在页面展示列表,列表需要分页滚动加载;一般情况下整个页面滚动可以直接在onReachBottom中直接实现,但是需求不能滚动整个页面;所以需要采用scroll-view控件进行操作;

首先,先看下页面基本的布局情况:

<template>
    <view style="position: fixed; 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;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中首先判断是否有新数据并且没有正在加载数据,然后再调用方法加载新数据;

原文地址:https://www.cnblogs.com/mrcui/p/15822821.html