小程序 – 上拉加载数据-案例

案例效果

步骤

① 定义获取随机颜色的方法

② 在页面加载时获取初始数据

③ 渲染 UI 结构并美化页面效果

④ 在上拉触底时调用获取随机颜色的方法

⑤ 添加 loading 提示效果

⑥ 对上拉触底进行节流处理

api地址:https://www.escook.cn/api/color

 

定义获取随机颜色的方法

定义请求方法:

getColor:() => {
    wx.request({
      url: 'https://www.escook.cn/api/color',
      method: 'GET',
      success: ({data:res}) => {
        this.setData({
          colorList: [...this.colorList,res.data]
        })
      }
    })
  },

 

在页面加载时获取初始数据

  onLoad(options) {
    this.getColor()
  },

 

渲染 UI 结构并美化页面效果

<text wx:for="{{ colorList }}" 
          wx:key="index" 
          class="num-item" 
          style="background-color: rgba({{ item }}, 1);"
>
          {{ item }}
</text>

CSS 设置样式

.num-item{
  border: 1rpx solid #efefef;
  border-radius: 8rpx;
  line-height: 200rpx;
  margin: 15rpx;
  text-align: center;
  text-shadow: 0rpx 0rpx 5rpx #fff;
  box-shadow: 1rpx 1rpx 6rpx #aaa;
}

 

在上拉触底时调用获取随机颜色的方法

  onReachBottom() {
    this.getColor()
  },

 

添加 loading 提示效果

通过调用 wx.showLoading() 方法显示加载中图层,调用wx.hideLoading() 关闭加载中图层,可在请求时加入这两个方法

getColor:() => {
    wx.showLoading()
    wx.request({
      url: 'https://www.escook.cn/api/color',
      method: 'GET',
      success: ({data:res}) => {
        this.setData({
          colorList: [...this.colorList,res.data]
        })
      },
      complete:()=>{
        wx.hideLoading()
      }
    })
  },

 

对上拉触底进行节流处理

当多次往上拉时,会多次触发调用 onReachBottom() 方法,会多次请求。需要做一个节流处理。

通过自定义 isLoading 属性,当在请求时,把 isLoading  设为 true。当请求完成后,把 isLoading 设为 false

getColor:() => {
    this.isLoading = true
    wx.showLoading()
    ....
      complete:()=>{
        wx.hideLoading()
        this.isLoading = false
      }
    })
  },

 

onReachBottom() 中判断 isLoading 是否为 true ,若是,则不进行加搬东西操作

  onReachBottom() {
    if(this.isLoading) return;
    this.getColor()
  }

 

如果您喜欢本站,点击这儿不花一分钱捐赠本站

这些信息可能会帮助到你: 下载帮助 | 报毒说明 | 进站必看

修改版本安卓软件,加群提示为修改者自留,非本站信息,注意鉴别

THE END
分享
二维码
打赏
海报
小程序 – 上拉加载数据-案例
本文为上拉加载数据案例
<<上一篇
下一篇>>