在智能小程序的开发过程中,上拉加载是一种十分常见的加载效果,最近也收到了一些开发者在开发上拉加载时遇到的问题,今天的内容就为您介绍一下如果想实现上拉加载,我们需要如何去做。
以下是为大家总结的四种常见的实现方式:
使用 onReachBottom 实现
使用 scroll-view 组件实现
使用信息流模板实现上拉加载
使用 swiper 组件配合 onReachBottom 实现上拉加载
使用 onReachBottom 实现
智能小程序提供了onReachBottom,即页面上拉触底事件的处理函数。可以拿在 Page 中定义 onReachBottom 处理函数,监听该页面用户上拉触底事件,从而实现上拉加载。
为方便大家直接使用看到效果,将下述代码片段,直接导入开发者工具中运行查看即可: swanide://fragment/7e944c0c3785bbdf4437c672dd0dc8e41584413934361
工具下载链接:Windows /mac
代码解析
1、swan 文件是每个智能小程序页面的展现模板,类似于 Web 开发中的 HTML,所以我们先在 swan 文件中设置商品的展现样式:
<view class="goodsList"> <block s-for="item,index in goods"> <view class="goodsItem"> <view class="goodsImage"> <image src="{{item.img}}"></image> </view> <view class="goodsTitle"> <text>{{item.title}}</text> </view> </view> </block></view><view class="loading">努力加载中...</view>2、在 js 文件中使用onReachBottom事件,当页面滑动到页面底部时,请求下一页展示数据,即实现上拉加载的效果。
......onReachBottom() { //触底时继续请求下一页展示的数据 this.initData();}使用 scroll-view 组件实现
利用 scroll-view 组件实现上拉加载也是一种十分常见的方法,实现步骤与使用onReachBottom事件类似。
scroll-view是百度智能小程序提供的组件,可实现试图区域的横向滚动和竖向滚动。使用它的bindscrolltolower属性,当页面滚动到底部或右边的时候,则会触发scrolltolower事件,从而实现上拉加载的效果。
为方便大家直接使用看到效果,将下述代码片段,直接导入开发者工具中运行查看即可: swanide://fragment/fccd71b098a7d3921b9958ccd9dba1071584414516291
代码解析
在 swan 文件中使用 scroll-view 组件,设置商品的展现样式。当页面滑动至底部时,触发scrolltolower事件,实现试图区域的竖向滚动。
``` <view class="intro"> <scroll-view class="scrollview" scroll-y bindscrolltolower="scrolltolower" > <view class="goodsList"> <view s-for="item,index in goods"> <view class="goodsItem"> <view class="goodsImage"> <image src="{{item.img}}"></image> </view> <view class="goodsTitle"> <text>{{item.title}}</text> </view> </view> </view> </view> <view class="loading">努力加载中...</view> </scroll-view></view>```使用信息流模板实现上拉加载
信息流模版是百度智能小程序提供的组件,可配置上拉刷新、列表加载、上拉加载功能,适用于列表信息展示,并可放置在页面的任何部分。
与其它组件功能不同,使用信息流模板时需执行下述命令行,引入页面模板。
npm i @smt-ui-template/page-feed
并在进入page-feed文件夹后,执行下述命令行安装所有模板依赖。
npm i
为方便大家直接使用看到效果,将下述代码片段,直接导入开发者工具中运行查看即可: swanide://fragment/71af2b7f470b29b13f792c417fc5f03c1588757790402
代码解析
1、在 swan 文件中使用信息流模板,通过 smt-spin 组件加载更多数据。
<smt-feed class="smt-feed pull-down-refresh" pull-to-refresh bind:scrolltolower="scrollToLower" text="{{text}}" style="height: 100vh"> <!-- 信息流组件作为局部滚动组件,必须在它的父级或本身指定高度 --> <view class="goodsList"> <view s-for="item,index in goods"> <view class="goodsItem"> <view class="goodsImage"> <image src="{{item.img}}"></image> </view> <view class="goodsTitle"> <text>{{item.title}}</text> </view> </view> </view> </view> <smt-spin status="{{status}}" bind:tap="reload"></smt-spin></smt-feed>2、在js文件中,利用在smt-spin组件上绑定的事件,实现加载更多的数据。
......async scrollToLower() { &nbs

