下拉加載功能是非常常見(jiàn)的功能,簡(jiǎn)單寫一下自己的輪子
vue里data定義需要用到五個(gè)屬性
data() {
return {
list: [], // 拿到存放的list
page: 1, // 頁(yè)數(shù)
more: true, // 是否加載一個(gè)控制,避免重復(fù)觸發(fā)
nomore: false, // 已加載完,不再請(qǐng)求
times: true // 觸底加載完通知
}
}
在mounted里監(jiān)聽(tīng)scroll,destroyed里銷毀
mounted() {
window.addEventListener('scroll', this.onSrcoll)
},
destroyed() {
window.removeEventListener('scroll', this.onSrcoll)
}
接口的寫法
getMoneyHis() {
getMoneyh(this.page).then(res => {
// 只傳遞page,默認(rèn)拿取十條
if(res.data.errorCode === '0') {
if(res.data.data.list.length < 10) {
this.nomore = true // 如果這次拿回不足10條就表示后面沒(méi)有了
}
this.list = [...this.list, ...res.data.data.list] // 這里直接合并數(shù)組
}
})
},
滾動(dòng)條觸發(fā)方法
onSrcoll() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 距離頭部距離
var getWindowHeight = document.documentElement.clientHeight || document.body.clientHeight // 頁(yè)面的高度
var documentScrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight // 總距離
if (scrollTop + getWindowHeight === documentScrollHeight && this.nomore) {
if(this.times) {
Toast('沒(méi)有更多數(shù)據(jù)了') // 觸底提示
this.times = false
setTimeout(() => {
this.times = true // 把時(shí)間打開(kāi),不一直提示
}, 60000)
}
return
}
if(scrollTop + getWindowHeight >= (documentScrollHeight-500)) {
if(!this.more) return
this.more = false
if(this.nomore) return
this.page += 1
this.getMoneyHis()
setTimeout(() => {
this.more = true // 發(fā)請(qǐng)求的間隙
}, 500)
}
}