uniapp实现触底分页加载

uniapp实现触底分页加载

一、页面结构

假设我们有一个简单的列表页面,包含一个用于展示列表项的<view>和一个用于触发加载更多操作的触底事件的区域。

<template>
  <view>
    <view v-for="item in listData" :key="item.id">{{ item.text }}</view>
    <view class="loading-more" v-if="isLoadingMore">加载中...</view>
    <view class="no-more" v-if="isLastPage">没有更多数据了</view>
  </view>
</template>

二、数据和方法

script部分,定义数据和方法。

export default {
  data() {
    return {
      listData: [],
      page: 1,
      pageSize: 10,
      isLoadingMore: false,
      isLastPage: false
    };
  },
  methods: {
    // 加载更多数据的方法
    loadMoreData() {
      if (this.isLastPage || this.isLoadingMore) return;
      this.isLoadingMore = true;
      // 模拟请求后端接口获取数据
      setTimeout(() => {
        const newData = this.generateData();
        if (newData.length < this.pageSize) {
          this.isLastPage = true;
        }
        this.listData = this.listData.concat(newData);
        this.page++;
        this.isLoadingMore = false;
      }, 1000);
    },
    // 生成模拟数据的方法
    generateData() {
      const start = (this.page - 1) * this.pageSize;
      const end = start + this.pageSize;
      const data = [];
      for (let i = start; i < end; i++) {
        data.push({ id: i, text: `Item ${i}` });
      }
      return data;
    }
  }
};

三、样式部分

可以为加载中提示和没有更多数据提示添加一些样式。

.loading-more {
  text-align: center;
  margin-top: 10px;
}

.no-more {
  text-align: center;
  margin-top: 10px;
  color: gray;
}

四、触底事件绑定

在页面的onLoad生命周期钩子中绑定触底事件。

export default {
  //...
  onLoad() {
    uni.onReachBottom(() => {
      this.loadMoreData();
    });
  }
};

在上述代码中,通过设置pagepageSize来控制分页加载。当触底时,调用loadMoreData方法去获取更多数据。如果获取到的数据长度小于每页的数量,就判断为最后一页,并设置isLastPagetrue。同时,在加载数据过程中,设置isLoadingMoretrue来显示加载中提示,加载完成后设置为false

注意,在实际应用中,需要将模拟请求后端接口的部分替换为真实的接口调用。并且,根据后端接口的返回值来准确判断是否为最后一页。有些接口可能会在返回的数据中明确标识是否还有更多数据,或者通过返回的总数据量和当前页码、每页数量来计算是否为最后一页。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值