微信小程序-上拉加載更多(示例)


注:沒有給出wxss,我這里用了colorUi第三方的組件(loading)   ------------ 轉載請標注

一. 概念:

 scroll-view

  可滾動視圖區域。使用豎向滾動時,需要給scroll-view一個固定高度,通過 WXSS 設置 height。組件屬性的長度單位默認為px,2.4.0起支持傳入單位(rpx/px)

  具體參數:https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html

二.

1> wxml:

<scroll-view scroll-y bindscrolltoupper="scrollToUpper" bindscrolltolower="scrollToLower" scroll-with-animation="true" style="height: {{scrollViewHeight}}px;">
  <view class="cu-card case" wx:for="{{studentDatas}}" wx:key="id" id="a-{{item.id}}">
    <view class="cu-item shadow">
      <view class="image">
        <image src="https://ossweb-img.qq.com/images/lol/web201310/skin/big10006.jpg" mode="widthFix" lazy-load></image>
        <view class="cu-tag bg-blue">史詩</view>
        <view class="cu-bar bg-shadeBottom">
          <text class="text-cut">{{item.name}}</text>
        </view>
      </view>
    </view>
  </view>
  <!--  style="position:fixed; bottom:0; width: 750rpx; opacity:0.8;" -->
  <view hidden="{{!showLoading}}">
      <view class="cu-load bg-gray {{loadingState?'loading':'over'}}"></view>
  </view>
</scroll-view>

2> js:

Page({
  /**
   * 頁面的初始數據
   */
  data: {
    /* 加載狀態:加載中(false)或加載完畢(true) */
    loadingState: true,
    /* 加載中或加載完畢 */
    showLoading: false,
    /* 第一頁 */
    pageNo: 1,
    /* 每頁數據條數 */
    pageSize: 10,
    /* 是否還有數據 */
    noMore: true,
    /* 數組 */
    studentDatas: [],
    /* 獲取的高度 */
    scrollViewHeight: 0,
    /* 是否已被上拉 */
    isUpperPulled: false
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    /* 取得頁面高度 */
    wx.getSystemInfo({
        success: (res)=> {
            this.setData({
              scrollViewHeight: res.windowHeight
            });
        }
    });
    this.fetchDataList(this.data.pageNo,this.data.pageSize);
  },

  fetchDataList(pageNo,pageSize) {
    if(this.data.noMore){
      wx.request({
        url: 'https://zgxmcp.com/wxtestweb/wxtest/getDatas', //url
        method: 'GET', 
        header: { 'Content-Type': 'application/json'},
        data: {
          pageNo: pageNo,  
          pageSize: pageSize
        }, complete: (res)=> {
          /* 判斷網絡通訊狀態 */
          if(res.statusCode == '200'){
            const students = res.data.students
            if(students.length>0){
              if(students.length<10){
                this.setData({
                  loadingState: false,
                  showLoading: false,
                  noMore: false,
                  isUpperPulled: false,
                  studentDatas: this.data.studentDatas.concat(res.data.students)
                })
              }else{
                this.setData({
                  showLoading: false,
                  noMore: true,
                  isUpperPulled: false,
                  studentDatas: this.data.studentDatas.concat(res.data.students)
                })
              }
            }
          }else{
            console.log(res.statusCode)
            wx.showToast({
              title: "statusCode:"+res.statusCode,
              icon: 'none'
            })
          }
        }
      })
    }else{
      // 沒有更多數據
      setTimeout( () => {
        this.setData({
          showLoading: true
        })
      }, 1500)
    }
  },

  scrollToLower: function(){
    if(!this.data.isUpperPulled){
      this.setData({
        isUpperPulled: true,
        showLoading: true,
        pageNo: this.data.pageNo +1
      })
      this.fetchDataList(this.data.pageNo,this.data.pageSize)
    }
  }
})

3> 順便寫個后台的數據接口

package com.ewx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ewx.servlet.userinfo.Student;

/**
 * 分頁數據模擬
 * 
 * @author liuwl
 */
public class DataServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 設置字符集
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        
        // 獲取輸出
        PrintWriter out = resp.getWriter();

        JSONObject jsonObj = new JSONObject();

        int pageNo = Integer.valueOf(req.getParameter("pageNo"));
        
        List<Student> datas = makeData(pageNo);
        try {
            Thread.sleep(4000);
            jsonObj.put("pages", 3);
            jsonObj.put("pageNo", pageNo);
            jsonObj.put("students", datas);
        } catch (InterruptedException e) {}

        out.print(jsonObj);
    }

    static int num = 0;

    static List<Student> makeData(int pageNo) {

        int size = 0;

        if (1 == pageNo) {
            size = 10;
        } else if (2 == pageNo) {
            size = 10;
        } else if (3 == pageNo) {
            size = 10;
        } else if (4 == pageNo) {
            size = 5;
        } else {
            size = 0;
        }

        List<Student> students = new ArrayList<Student>();
        for (int i = 0; i < size; i++) {
            students.add(new Student(++num, "" + i, pageNo + "_姓名_" + i, i));
        }
        for (int i = 0; i < students.size(); i++) {
            System.out.println(students.get(i).toString());
        }
        return students;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

 

效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM