在使用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中首先判断是否有新数据并且没有正在加载数据,然后再调用方法加载新数据;
分类:
uniapp
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?