序
近期上線了一個(gè)微信小程序,于是罐孝,秉著互相學(xué)習(xí),互相進(jìn)步的態(tài)度狞尔,將常用的下拉刷新和觸底加載在這里發(fā)表一哈丛版。
效果圖
下拉刷新與觸底加載.gif
說明
由于下拉刷新和觸底加載大多用于從網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù),效果圖的實(shí)現(xiàn)偏序,去除了網(wǎng)絡(luò)页畦,通過定時(shí)器來達(dá)到這么個(gè)效果,但是說明原理足夠了研儒。
效果圖中用到的組件庫:
實(shí)現(xiàn)代碼
布局與樣式都很簡(jiǎn)單好芭,就不做展示了,只貼JS代碼冲呢,代碼中有簡(jiǎn)單注釋舍败。
const app = getApp()
const LIMIT = 4 //云開發(fā)請(qǐng)求時(shí)需要
Page({
data: {
list: [],
show_loading: true,
hide_nomore: true
},
elsedata: {
//只用于模擬實(shí)現(xiàn)效果,云開發(fā)不必
list_1: [1, 2, 3, 4],
list_2: [5, 6],
remain_page: 2,
//云開發(fā)時(shí)需要
skip: 0
},
onLoad: function() {
this.getList()
},
getList() {
//此處的數(shù)據(jù)判斷僅用于模擬敬拓,云開發(fā)時(shí)應(yīng)該用實(shí)際請(qǐng)求的數(shù)據(jù)做判斷
if (this.elsedata.remain_page > 0) {
let templist = this.data.list.length <= 0 ? this.elsedata.list_1 : this.data.list.concat(this.elsedata.list_2);
setTimeout(() => {
this.setData({
list: templist,
show_loading: false
})
this.elsedata.skip = this.elsedata.skip + LIMIT
this.elsedata.remain_page -= 1
}, 1000)
} else {
this.setData({
show_loading: false,
hide_nomore: false
})
}
},
//下拉刷新
onPullDownRefresh: function() {
if (this.data.list.length <= 0) {
wx.stopPullDownRefresh()
return
}
this.setData({
hide_nomore: true
})
wx.showLoading({
title: '請(qǐng)求中',
mask: true
})
this.elsedata.remain_page = 2 //云開發(fā)時(shí)不必
this.pullGetData(res => {
this.elsedata.skip = LIMIT
this.elsedata.remain_page -= 1 //云開發(fā)時(shí)不必
wx.hideLoading()
wx.stopPullDownRefresh()
})
},
pullGetData: function(callback) {
let tempres = this.elsedata.list_1 //云開發(fā)時(shí)需要使用實(shí)際數(shù)據(jù)
//定時(shí)器也只是為了模擬效果
setTimeout(() => {
this.setData({
list: tempres
}, res => {
callback();
})
}, 1000)
},
//觸底加載
onReachBottom: function() {
if (this.data.show_loading)
return
if (!this.data.hide_nomore)
return
this.setData({
show_loading: true,
hide_nomore: true
})
this.getList()
}
})