Апплет WeChat реализует ленивую загрузку и метод добавления данных

В бизнесе мы часто сталкиваемся со списком со многими изображениями или данными. Если он отображается за один раз, время рендеринга может быть слишком большим, или он может напрямую ударить по белому экрану, и ничего не может быть отображено. В это время ленивый загрузка (только рендеринг вида Данные в рот) очень нужна, а потом каждый раз добавлять определенное количество штук.

Идея:
введите инициализацию страницы, сначала загрузите первые 10 массивов voiceList (количество основано на фактических потребностях), а затем всякий раз, когда пользователь опускает вниз, запускайте функцию onReachBottom, добавляйте последние 10 массивов voiceList и циклически выполняйте до тех пор, пока все загружены, отображается «Все загружено» и другие подсказки не могут быть сняты в это время.

Код:
wxml:

<view class="vote_list flex-row">
    <view class="item" wx:for="{
     
     {voteList}}" wx:key="{
     
     {item.contentId}}">
      <view class="image" bindtap="popupVideo" data-item="{
     
     {item}}" >
        <image class="img" mode="widthFix" src="{
     
     {item.contentpic50}}"></image>
        <image class="play_icon" src="../../images/video-icon.png"></image>
      </view>
      <view class="title" bindtap="popupVideo" data-item="{
     
     {item}}"><text>{
   
   {item.contentname}}</text></view>
      <view class="author">{
   
   {item.authorName}}</view>
    </view>
  </view>

js:

var api = require('../../api.js');
var MD5 = require('../../utils/MD5.js');
var app = getApp();
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    Phone: '',
    token: '',
    voteList: [],
    allList: [],
    currentNo: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    
    var Phone = wx.getStorageSync('Phone')
    this.setData({
    
    
      Phone: Phone
    })
    this.getList()
  },

  // 列表
  getList() {
    
    
    var that = this
    wx.request({
    
    
      url: api.wx.getVoteList
      method: 'get',
      data: app.getNewMD5({
    
    
        t: that.data.token
      }),
      success: function (res) {
    
    
        // console.log(res.data.data.content)
        if (res.data.code == '200') {
    
    
          var totalList = res.data.data.content
          var initList = []
          for (var i = 0; i < 10; i++) {
    
    
            initList.push(totalList[i])
          }
          that.setData({
    
    
            voteList: initList,
            allList: res.data.data.content
          })
          console.log(that.data.voteList)
        }
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
    
    var allList = this.data.allList
    var currentNo = this.data.currentNo
    var initList = []
    console.log(currentNo, allList.length)
    // 剩余条数
    var surplus = allList.length - currentNo
    if (surplus >= 10) {
    
    
      for (var i = 0; i < currentNo + 10; i++) {
    
    
        initList.push(allList[i])
      }
      console.log('initList', initList)
      this.setData({
    
    
        currentNo: currentNo + 10,
        voteList: initList
      })
    } else {
    
    
      for (var i = 0; i < currentNo + surplus; i++) {
    
    
        initList.push(allList[i])
      }
      console.log('initList', initList)
      this.setData({
    
    
        currentNo: currentNo + surplus,
        voteList: initList
      })
    }
  }

})

Guess you like

Origin blog.csdn.net/joe0235/article/details/122057131