下拉加載列表

下拉加載功能是非常常見(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)
      }

    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容