小程序上拉加载、下拉刷新的使用方法

一、定义数据

data() {
  return {
    list: [],      //数据列表
    noMore: false, // 全部加载后底部提示
    total: 0,      // 总条数
    data: {
      page: 1,    // 页码
      limit: 10   // 每次请求数量
    },
  };
},

二、启用下拉刷新 

在页面的 .json 配置文件中,将 enablePullDownRefresh 设置为 true

三、监听下拉刷新 

操作下拉刷新时,设置当前页数、总数、请求列表清零等

再次发起请求,请求完毕停止下拉刷新效果

onPullDownRefresh() {
  this.data.page = 1
  this.total = 0
  this.list = []
  this.record()
  uni.stopPullDownRefresh()
},

四、上拉触底加载

onReachBottom() {
  if (this.data.page * this.data.limit >= this.total) {
    this.noMore = true
    return
  }
  this.data.page++ // 让页码值自增+1
  this.record()
},

五、初次加载页面的操作

首次加载页面请求数据后,进行判断:如果数据请求完毕显示‘没有更多了’

onLoad: function(options) {
  this.recordList();
  if (this.data.page * this.data.limit >= this.total) {
    this.noMore = true
    return
  }
},

六、调接口拿数据

每次请求十条数据,并添加到数据列表中

async recordList() {
  const res = await uni.$http.get('/api/recordList', this.data)
  // console.log(res.data); // 每次请求返回十条数据
  if (res.statusCode !== 200) return uni.$showErrorMsg("获取充值记录失败")
  this.list = [...this.list, ...res.data.records]
  this.total = res.data.total   // 通过接口获取总条数
},

七、全部代码

<template>
  <view class="content">
    <uni-row v-for="(item, index) in list" :key="item.index">
       ... ...(需要渲染的数据)
    </uni-row>
    <view class="bottom" v-if="noMore">
      没有更多了
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        list: [],
        noMore: false,
        data: {
          page: 1,
          limit: 12
        },
        total: 0,
      };
    },
    onLoad: function(options) {
      this.recordList();
      if (this.data.page * this.data.limit >= this.total) {
        this.noMore = true
        return
      }
    },
    methods: {
      async recordList() {
        const res = await uni.$http.get('/api/recordList', this.data)
        // console.log(res.data); // 每次请求是十条数据
        if (res.statusCode !== 200) return uni.$showErrorMsg("获取记录失败")
        this.list = [...this.list, ...res.data.records]
        this.total = res.data.total
      },

      onPullDownRefresh() {
        this.data.page = 1
        this.total = 0
        this.list = []
        this.record()
        setTimeout(() => {
          uni.stopPullDownRefresh()
        }, 1000);
      },
        
      onReachBottom() {
        if (this.data.page * this.data.limit >= this.total) {
          this.noMore = true
          return
        }
        this.data.page++ // 让页码值自增+1
        this.record()
      },
    }
  }
</script>

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋绥冬禧.

一键三联就是最大的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值