基于vue-infinite-loading的上拉加載

前言:

最近需要做一個消息上拉加載的功能,查詢資料后發(fā)現(xiàn)vue-infinite-loading最好做。不過中間遇到部分難點(diǎn),目前未發(fā)現(xiàn)文章有詳細(xì)解決代碼,為了后面的小伙伴方便,大概整理了一下。

測試文件全部代碼
<template>
  <div class="chat-window" ref="list">
    <infinite-loading
      :on-infinite="infiniteHandler"
      force-use-infinite-wrapper=".chat-window"
      direction="top"
      ref="infiniteLoading"
    >
      <div slot="spinner">小弟拼命加載中...</div>
      <div slot="no-more">已加載完畢!</div>
      <div slot="no-results">暫無數(shù)據(jù):(</div>
    </infinite-loading>
    <div v-for="(item, $index) in list" :key="$index">
      {{`第${item}條數(shù)據(jù)`}}
    </div>
  </div>
</template>

<script>
import InfiniteLoading from "vue-infinite-loading"; // 滾動加載 https://peachscript.github.io/vue-infinite-loading/guide/#import

export default {
  name: "ChatMessage1",
  components: { InfiniteLoading },
  data() {
    return {
      num: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      list: [],
      lastHeight: 0
    };
  },
  methods: {
    infiniteHandler($state) {
      let _this = this;
      const temp = [];     
      for (let i = this.list.length + 1; i <= this.list.length + 10; i++) {         
        temp.unshift(i);       
      }       
      this.list = temp.concat(this.list);
      if(this.$refs.list.scrollHeight > this.lastHeight) {
        this.$refs.list.scrollTop = this.$refs.list.scrollHeight - this.lastHeight;
        this.lastHeight = this.$refs.list.scrollHeight;
        $state.loaded();
      } else {
        $state.loaded();
      }
      if(this.list.length > 80) {
        $state.complete();
        return;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.lastHeight = this.$refs.list.clientHeight;
    })
  }
};
</script>
<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  /height: 100%; 
  overflow-x: hidden;
  overflow-y: auto; 
}
</style>

幾處重點(diǎn)

1、force-use-infinite-wrapper屬性
image.png

以上為官網(wǎng)解釋,即主要用于標(biāo)記容器

2、lastHeight意義(重點(diǎn)***)

初次定義為容器高度,在滾動條高度高于容易高度時,將滾動條移到高出的位置,即第一次超出會移動到最底部。

    if(this.$refs.list.scrollHeight > this.lastHeight) {
      this.$refs.list.scrollTop = this.$refs.list.scrollHeight - this.lastHeight;
        this.lastHeight = this.$refs.list.scrollHeight;
        $state.loaded();
      } else {
        $state.loaded();
      }

隨后將lastHeight設(shè)為當(dāng)前滾動條高度。如果再次觸發(fā)上拉加載,再用加載后的滾動條高度減去lastHeight,這樣頁面就會處于加載后新數(shù)據(jù)的底部位置,不會再次觸發(fā)上拉。除非繼續(xù)上拉滾動條。這樣功能就基本完成了。

3、$state.complete()

此方法主要用于終止上拉組件,在需要終止的邏輯下使用即可。另外幾個slot插槽可再官方文檔查看詳細(xì)使用方法。在這不贅述了。

希望能幫到大家~

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

相關(guān)閱讀更多精彩內(nèi)容

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