**需求:**後臺接口沒有做分頁處理,直接傳來了很多條數據(幾千上萬條),會造成小程序渲染卡頓,頁面空白;
**解決:**接口傳來的數據接收後存到數組裏,自定義懶加載分頁請求功能,每次滾到底部,再去請求下頁數據;
data(){
return{
dataList: [], //頁面渲染時存放的數據
_dataList: null,//接口傳來的數據存放數組
currentPageNum: 1,//當前頁
}
}
setData (data = []) {
this.dataList = []
this._dataList = null
if (data && data.length > 99) { // 數量超過100條,懶加載分頁
let arr = []
let len = Math.ceil(data.length / 20)
for (let i = 0; i < len; i++) {
arr[i] = data.slice(i * 20, (i + 1) * 20)
}
this._dataList = arr
this.dataList = this._dataList[0]
} else if (data) {
this.dataList = data
}
setTimeout(() => {
mpvue.hideLoading()
}, 1000)
},
小程序自帶方法onReachBottom ,到達底部時觸發
onReachBottom () {
if (this._dataList && (this.currentPageNum < this._dataList.length)) {
mpvue.showLoading({
mask: true,
title: '加載中!'
})
let nextPageNum = this.currentPageNum++
let arr = this._dataList[nextPageNum]
for (let i = 0; i < 20; i++) {
this.dataList.push(arr[i])
}
setTimeout(() => {
mpvue.hideLoading()
}, 500)
}
}
注:儘量還是讓後端接口實現分頁功能,這纔是王道!