背景
使用此組件需要依賴小程序基礎庫 2.2.2 版本,同時依賴開發者工具的 npm 構建。具體詳情可查閱官方 npm 文檔。
目前小程序會有不少的應用場景裏會用到無限長列表的交互,當一個頁面展示很多信息的時候,會造成小程序頁面的卡頓以及白屏。因此就有長列表組件來解決這些問題。
1. 安裝組件
npm install --save miniprogram-recycle-view
2. 在頁面的 json 配置文件中添加 recycle-view 和 recycle-item 自定義組件的配置
{
"usingComponents": {
"recycle-view": "miniprogram-recycle-view/recycle-view",
"recycle-item": "miniprogram-recycle-view/recycle-item"
}
}
3. WXML 文件中引用 recycle-view
<recycle-view height='{{height_g}}' batch="{{batchSetRecycleData}}" id="recycleId">
<view slot="before">長列表前面的內容</view>
<recycle-item wx:for="{{recycleList}}" wx:key="id">
<view>
<image style='width:80px;height:80px;float:left;' src="{{item.image_url}}"></image>
{{item.idx+1}}. {{item.title}}
</view>
</recycle-item>
<view slot="after">長列表後面的內容</view>
</recycle-view>
//標籤對的height需要設置,否則滑動到最後可能部分數據無法顯示
4.頁面 JS 管理 recycle-view 的數據
const createRecycleContext = require('miniprogram-recycle-view');
const W = wx.getSystemInfoSync().windowWidth;
const rate = 750 / W;
const code_w1 = 690 / rate; //把每個列表的寬高轉爲px單位
const code_h1 = 120 / rate;
Page({
data: {
page_index: 1, //當前頁碼
lodeing:true,
height_g:0
},
onLoad: function (options) {
let that=this;
// 轉換列表高度爲px,用於設置上面標籤對的高度
wx.getSystemInfo({
success(res) {
console.log(res.windowHeight)
let height = 608 / rate
that.setData({
height_g: res.windowHeight-height
})
}
})
},
getRankingList: function () {
var that = this;
//防止重複加載
if (!that.data.lodeing) {
return false;
}
that.setData({
lodeing: false
})
wx.showLoading({
title: '加載中...',
})
if (that.data.page_is_end) {
wx.hideLoading()
wx.showToast({
title: '加載完畢',
});
return false;
}
wx.request({
url: api.getRankingListBytype,
dataType: 'json',
data: {
offset: that.data.page_index,//當前頁碼
time: ''
},
success: function (res) {
if (res.data.code == 200) {
wx.hideLoading()
//根據頁碼做排重
if (res.data.data.page_index + 1 == that.data.page_index) {
return false;
}
ctx = createRecycleContext({
id: 'recycleId', //對應wxml中設置的id
dataKey: 'recycleList', //wxml中wx:for的值
page: that,
itemSize: {
width: code_w1, //上面轉換後的寬和高
height: code_h1
}
})
ctx.append(res.data.data.ranking_list) //賦值
that.setData({
page_index: that.data.page_index + 1, //頁碼+1
page_is_end: res.data.data.ranking_list.length < res.data.data.page_size ? true : false, //判斷返回的數據總數是否小於設置的每頁總數量的值,如果小於的話說明後面每頁數據了,可以停止加載了
lodeing: true //賦值完成後設置爲true,說明可以加載下一頁了
})
}else{
wx.showModal({
title: '提示',
content: res.data.message,
showCancel: false
})
wx.hideLoading()
}
},
complete: function (res) {
}
});
},
})