微信小程序实现懒加载追加数据方法
业务中我们常会遇到图片较多、或者数据较多的列表,一次渲染出来的话轻则渲染时间过长,重则可能直接罢工白屏,什么都渲染不出来,这个时候懒加载(只渲染视口中的数据)就很有必要了,然后每次再追加一定的条数。
思路:
进入页面初始化,首先 voteList 数组
加载前10条(数量根据实际需要),然后每当用户下拉到底部后,触发onReachBottom
函数,追加后10条到 voteList 数组
中,循环直到全部加载完毕,显示“全部加载完毕”等提示语,此时无法下拉。
代码:
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 }) } } })