微信小程序实现上拉加载更多

news2024/9/23 13:25:18

一、前情提要

  1. 微信小程序中实现上拉加载更多,其实就是pc端项目的分页。
  2. 使用的是scroll-view,scroll-view详情在微信开发文档/开发/组件/视图容器中。
  3. 每次上拉,就是在原有数据基础上,拼接/合并上本次上拉请求得到的数据。
  4. 这里采用的是concat,concat 是数组对象的一个方法,用于合并两个或多个数组,生成一个新的数组。这个方法不会修改原始数组,而是返回一个新的数组
  5. concat使用示例如下:
// 示例数组
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];

// 使用concat合并数组
const mergedArray = array1.concat(array2, array3);

// 打印结果
console.log("原始数组1: ", array1);
console.log("原始数组2: ", array2);
console.log("原始数组3: ", array3);
console.log("合并后的数组: ", mergedArray);

//输出结果应为:
原始数组1:  [1, 2, 3]
原始数组2:  [4, 5, 6]
原始数组3:  [7, 8, 9]
合并后的数组:  [1, 2, 3, 4, 5, 6, 7, 8, 9]

二、代码示例(1)不使用onReachBottom

  1. index.wxml
//1、scroll-y 允许纵向滚动
//2、lower-threshold="100px" 距底部/右边多远(100px)时,触发 scrolltolower 事件
//3、scroll-top="{{topHeight}}px" 设置竖向滚动条位置
<view class="box">
	<!-- 列表 -->
	<scroll-view scroll-y lower-threshold="100px" bindscrolltolower="scrollToLower" style="height: 80vh;" scroll-top="{{topHeight}}px" class="scrView">
		<view class="listBox" wx:for="{{groupData}}" wx:key="id">
			<view class="name">{{item.name}}</view>
			<view class="phone">{{item.mobile}}</view>
			<image src="../../image/icon/bj.png" bindtap="editRecipient" data-item="{{item}}" class="mini-btn" />
			<image src="../../image/icon/sc.png" bindtap="deleteRecipient" data-id="{{item.id}}" class="mini-btn2" />
		</view>
		<view style="text-align: center;">
            <view wx:if="{{loading}}">加载中...</view>
            <view wx:if="{{noMore && !noData}}">没有更多了</view>
            <view wx:if="{{noData}}">暂无数据</view>
        </view>
	</scroll-view>
</view>
  1. index.js
Page({
  data: {
   loading: false, //加载更多的loading
   noMore: false,   //没有更多了
   noData:false, //暂无数据
   isPage:false, // 是否需要分页 ispage的作用 进页面首次在onLoad中调用时,不需要合并数据
   page:1,
   limit:5,
   topHeight:0, 
 },
 /**
  * 生命周期函数--监听页面加载
  */
 onLoad(options) {
   this.getContactList()
 },
 // restore函数的作用,当业务有搜索、删除、新增、编辑等操作时,需要还原对应参数状态。
 // 初始化数据
 restore(){
   this.setData({
     loading: false, //加载更多的loading
     noMore: false,   //没有更多了
     noData:false,
     isPage:false,
     page:1,
     limit:5,
     topHeight:0, 
   })
 },
 getContactList(isPage){
   let params = {
     page:this.data.page,
     limit:this.data.limit,
     tid: this.data.inquirFform.tagID
   }
   req.group.contactList(params).then((res) =>{

     if (isPage) {
       // 下一页数据拼接在原始数据后面
       this.setData({
         groupData: this.data.groupData.concat(res.data.list),
         loading: false
       })
     } else {
       this.setData({
         groupData: res.data.list,
         loading: false
       })
     }
     //如果返回的数据为空,那么就没有下一页了
     if (res.data.list.length == 0 && this.data.isPage) {
       this.setData({
         noMore: true
       })
     }
     if (res.data.list.length == 0 && !this.data.isPage) {
       this.setData({
         noMore: true,
         noData:true
       })
     }
   })
 },
 // 下滑到底部触发
 scrollToLower(){
   if (!this.data.loading && !this.data.noMore) {
     this.setData({
       loading: true,
       page: this.data.page + 1,
       isPage:true
     })
     this.getContactList(this.data.isPage)
   }
 },
})

示例图片如下:
请添加图片描述

三、代码示例(2)使用onReachBottom(1)

onReachBottom:监听用户上拉触底事件。
可以在app.json的window选项中或页面配置中设置触发距离onReachBottomDistance。
在触发距离内滑动期间,本事件只会被触发一次。

  • 每次请求数据时候,在底部提示加载中

  • 当请求完全部数据时,在底部提示 没有更多数据了,
    后端返回数据总条数 如下.js文件中的 total 判断 每次请求时判断前端拿到的总数据的length == total,若是等于 则显示 没有更多数据了,并且 再次上拉时,不进行数据的请求。

  • 前端传 page 当前页 每次请求 page + 1
    limit:没有数量 前端自己写个固定值就行
    业务参数:若列表支持查询搜索等,传自己的业务数据

  • 后端返回 total:总数据条数
    data:[] 对应的数据列表

  • 有导航切换的需要注意,切换导航后先重置 加载中提示,没有更多数据提示,page等参数后,在请求数据

、、、
1、wxml

<view class="content">
    <view class="body">
      <view class="box" wx:for="{{proArr}}" wx:key="_id">
        <xzs-product-item item="{{item}}"></xzs-product-item>
      </view>
    </view>
    <view class="loadOut">
      <van-loading size="24px" wx:if="{{loading}}">加载中...</van-loading>
      <view class="noData" wx:if="{{isData}}">没有更多数据了~</view>
    </view>
</view>
```';

3、.js


Page({

  /**
 * 页面的初始数据
   */
  data: {
    navActive:0,
    navArr:[],

    proArr:[],
    page:1,
    limit:10,
    loading:false,
    isData:false
  },

  /**
 * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let {idx} = options;    
    await this.getNavList(); 
    if(idx){
      this.navChange(idx);
    }else{
      navid = this.data.navArr[0]._id;
      this.getProductList();
    }
  },
  //获取产品列表
  getProductList(){
    this.setData({
      loading:true
    })
    queryProduct({
      navid:navid,
      page:this.data.page,
      limit:this.data.limit
    }).then(res=>{   
      let oldArr= this.data.proArr;
      let newArr=oldArr.concat(res.data)   
      console.log(res);
      this.setData({
        proArr:newArr,
        loading:false
      })
      if(res.total == this.data.proArr.length){
        this.setData({
          isData:true
        })
      }
    })
  },

  //导航条切换事件
  navChange(e){    
    let index= e?.detail?.index ?? e;
    navid = this.data.navArr[index]._id
    this.setData({
      proArr:[],
      loading:false,
      isData:false,
      page:1,
      navActive:Number(index)
    })    
    this.getProductList();
  },
  /**
 * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.isData) return;
    this.setData({
      page:this.data.page + 1})
    this.getProductList()
  },
})

四、代码示例(2)使用onReachBottom(2)

  • 这个同 三、代码示例(2)类似,只不过是请求时传递给后端的参数不同
  • 前端传 size: 就是列表数据的长度,初始是0。例如:第一次,请求得到数据长度为5 ,那么上拉数据请求时候,size就传5,再次上拉,合并数据后长度为10,下次上拉请求就传10

1、.wxml

<view class="content">
    <view class="body">
      <view class="box" wx:for="{{proArr}}" wx:key="_id">
        <xzs-product-item item="{{item}}"></xzs-product-item>
      </view>
    </view>
    <view class="loadOut">
      <van-loading size="24px" wx:if="{{loading}}">加载中...</van-loading>
      <view class="noData" wx:if="{{isData}}">没有更多数据了~</view>
    </view>
</view>

2、.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navActive:0,
    navArr:[],
    proArr:[],
    loading:false,
    isData:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
      this.getProductList();
  },
  //获取产品列表
  getProductList(s=0){
    this.setData({
      loading:true
    })
    queryProduct({
      navid:navid,
      size:s
    }).then(res=>{   
      let oldArr= this.data.proArr;
      let newArr=oldArr.concat(res.data)   
      console.log(res);
      this.setData({
        proArr:newArr,
        loading:false
      })
      if(res.total == this.data.proArr.length){
        this.setData({
          isData:true
        })
      }
    })
  },

  //导航条切换事件
  navChange(e){    
    let index= e?.detail?.index ?? e;
    navid = this.data.navArr[index]._id
    this.setData({
      proArr:[],
      loading:false,
      isData:false,
      navActive:Number(index)
    })    
    this.getProductList();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.isData) return;
    this.getProductList(this.data.proArr.length)
  }
})

三和四几乎一样,就看前后端怎么约定的穿什么数据,返回什么数据

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1502783.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

搜狐新闻Hybrid AI引擎端侧离线大语言模型探索

本文字数&#xff1a;3027字 预计阅读时间&#xff1a;20分钟 01 一、导读 • LLM 以及移动平台落地趋势 • 搜狐AI引擎内建集成离线可运行的GPT模型 • Keras 定制预训练模型 • TensorFlow Lite converter 迁移到移动设备 02 二、LLM 1.1什么是LLM L…

HTML入门:属性

你好&#xff0c;我是云桃桃。今天来聊一聊 HTML 属性写法和特点。 HTML 属性是用于向 HTML 标签&#xff08;也叫 HTML 元素&#xff09;提供附加信息或配置的特性。 如果说&#xff0c;把HTML 标签比作一个房子&#xff0c;HTML 标签定义了房子的结构和用途&#xff0c;比如…

蓝桥杯之【01背包模版】牛客例题展示

牛客链接 #include <bits/stdc.h> using namespace std; int n,V; const int N1010; int v[N],w[N]; int dp[N][N]; int main() {cin>>n>>V;for(int i1;i<n;i){cin>>v[i]>>w[i];}for(int i1;i<n;i){for(int j1;j<V;j){dp[i][j]dp[i-1][…

idea远程服务器debug

前提 本地代码和服务器代码一致 idea中创建远程服务 一般只需要修改ip&#xff0c;注意这边的端口是监听Socket的端口&#xff0c;不是服务的端口 然后把运行参数复制一下 -agentlib:jdwptransportdt_socket,servery,suspendn,address5005 tomcat启动 在tomcat的lib下的c…

OJ_二叉排序树

题干 C实现 循环双指针法(一个指向父亲&#xff0c;一个指向待插入结点) #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <queue> using namespace std;struct TreeNode {char data;TreeNode* left;TreeNode* right; };void InsertBST(TreeNode* …

扩展黄永刚原始晶体塑性程序加入AF背应力模拟金属疲劳问题

参考文献&#xff1a;《Low-cycle fatigue life prediction of a polycrystalline nickel-base superalloy using crystal plasticity modelling approach》 在原始程序中修改流动方程&#xff0c;加入背应力项&#xff0c;引入运动硬化项&#xff0c;从而可以描述多晶金属循环…

智慧公厕系统的运作过程

智慧公厕是一种新型的未来城市公共厕所&#xff0c;通过物联网、互联网、大数据、云计算、自动化控制等技术&#xff0c;实现公共厕所使用、运营、管理、养护的全过程全方位信息化。 那么&#xff0c;智慧公厕是如何运作的&#xff1f;智慧公厕的运作过程包括什么技术&#xf…

悬浮工具球(仿 iphone 辅助触控)

悬浮工具球&#xff08;仿 iphone 辅助触控&#xff09; 兼容移动端 touch 事件点击元素以外位置收起解决鼠标抬起触发元素的点击事件问题 Demo Github <template><divref"FloatingBal"class"floating_ball":class"[dragging, isClick]&q…

【Docker4】使用Harbor搭建私有仓库

Docker私有仓库一、搭建本地私有仓库1、daemon.json 配置文件中常用配置项2、搭建私有仓库3、Docker容器重启策略 二、Docker--harbor私有仓库部署与管理1、Harbor 简介2、Harbor的特性3、Harbor的构成4、Harbor 部署4.1、部署 Docker-Compose 服务4.2、部署 Harbor 服务4.3、启…

OJ_判断两序列是否为同一二叉搜索树序列

题干 C实现 求出两棵树的中序和先序序列对比中序和先序序列是否相同 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string> #include <queue> using namespace std;struct TreeNode {char data;TreeNode* left;TreeNode* right; };void …

day17_订单(结算,提交订单,支付页,立即购买,我的订单)

文章目录 订单模块1 结算1.1 需求说明1.2 获取用户地址1.2.1 UserAddress1.2.2 UserAddressController1.2.3 UserAddressService1.2.4 UserAddressMapper1.2.5 UserAddressMapper.xml 1.3 获取购物项数据1.3.1 CartController1.3.2 CartService1.3.3 openFeign接口定义 1.4 环境…

VUE_nuxt启动只能通过localhost访问,ip访问不到:问题解决

修改项目根目录下的 package.json "config": {"nuxt": {"host": "0.0.0.0","port": "3000"} } 这样项目启动后就可以通过ip进行访问了

ViewModel

1.ViewModel的诞生与作用 Activity package com.tiger.viewmodel;import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider;import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Te…

Codeforces Round 929 (Div. 3)- ABCDEFG

A:Turtle Puzzle: Rearrange and Negate 思路&#xff1a; 将负的元素全部排到一起&#xff0c;然后对它们符号取反&#xff0c;然后求所有元素的和&#xff0c;此时就是最大值了。 代码&#xff1a; #include<iostream> using namespace std;void solve() {int n;cin&…

电脑资料管理软件(5个高效批量管理电脑资料的方法)

企业电脑资料管理是企业一大难题&#xff0c;为什么这样说&#xff1f; 首先&#xff0c;企业电脑资料的数量庞大且种类繁多。 其次&#xff0c;电脑资料的安全性和保密性要求高。 再者&#xff0c;电脑资料的管理涉及到多个部门和员工的协作。 ...... 针对此类情况很多企业…

Vue中的组件:构建现代Web应用的基石

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

基于redis实现互斥锁

利用setnx命令实现类似获取锁和释放锁。 获取锁&#xff0c;setnx lock 1&#xff0c;返回值为1视为获取成功&#xff0c;为0视为获取失败 释放锁&#xff0c;del lock 特殊情况&#xff1a; 如果获取锁之后&#xff0c;锁来还来不及释放&#xff0c;redis宕机了&#xff0c;这…

MIT6.5840(6.824)Lab2总结(Raft)

MIT6.5840&#xff08;原MIT6.824&#xff09;Lab2总结&#xff08;Raft&#xff09; 资源分享&#xff1a; 官网地址&#xff1a;http://nil.csail.mit.edu/6.5840/2023/ Raft论文地址&#xff1a;http://nil.csail.mit.edu/6.5840/2023/papers/raft-extended.pdf 官方学生…

gumbel-softmax如何实现离散分布可微+torch代码+原理+证明

文章目录 背景方法通俗理解什么是重参数化gumbel-softmax为什么是gumbeltorch实现思考 背景 这里举一个简单的情况&#xff0c;当前我们有p1, p2, p3三个概率&#xff0c;我们需要得到最优的一个即max(p1, p2, p3)&#xff0c;例如当前p3 max(p1, p2, p3)&#xff0c;那么理想…

SSRF漏洞基础原理(浅层面解释 + 靶场演示)

一、SSRF漏洞的基本概念&#xff1a; SSRF--全名&#xff1a;Server-Side Request Forgery&#xff0c;汉译&#xff1a;服务端请求伪造&#xff0c;漏洞别名“借刀杀人”。 想象以下&#xff0c;现存在一个 Web应用&#xff0c;这个Web应用可以帮助我们能爬取互联网上的其他…