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

一、定义数据

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>

猜你喜欢

转载自blog.csdn.net/m0_61663332/article/details/130265775