VUE實現 上滑加載更多

實現HTML5頁面上滑加載更多功能的方案:

1. 頁面結構

<div id="content-container">
  <div class="item" v-for="(item, index) in items" :key="index">
    <!-- 在這裏渲染單個數據項的內容 -->
  </div>
</div>

<!-- 加載提示區域 -->
<div id="load-more" v-if="loadingMore">
  <p>Loading...</p>
</div>

2. JavaScript(假設使用Vue.js作爲示例框架)

const app = new Vue({
  el: '#app',
  data() {
    return {
      items: [], // 存儲已加載的數據項
      page: 1, // 當前請求頁碼
      loadingMore: false, // 是否正在加載更多
      hasMore: true, // 是否還有更多數據可供加載
    };
  },
  mounted() {
    this.fetchData();
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    fetchData() {
      this.loadingMore = true;
      axios.get(`your-api-url?page=${this.page}&limit=15`)
        .then(response => {
          const newItems = response.data.items; // 假設API返回數據結構中包含一個名爲items的數組
          if (newItems.length < 15) {
            this.hasMore = false; // 如果本次加載數量不足15條,說明已無更多數據
          }
          this.items.push(...newItems);
          this.page++;
          this.loadingMore = false;
        })
        .catch(error => {
          console.error('Error fetching more data:', error);
          this.loadingMore = false;
        });
    },
    handleScroll() {
      const contentContainer = document.getElementById('content-container');
      const threshold = 100;
      const { scrollTop, offsetHeight, scrollHeight } = contentContainer;
      const distanceFromBottom = scrollHeight - (scrollTop + offsetHeight);

      if (!this.loadingMore && distanceFromBottom <= threshold && this.hasMore) {
        this.fetchData();
      }
    },
  },
});

解釋說明

  • 頁面結構中,使用div#content-container來存放數據項,並通過v-for循環遍歷items數組進行渲染。同時,添加了一個div#load-more用於顯示加載中的提示,其顯示與否由loadingMore狀態控制。

  • JavaScript部分,我們創建了一個Vue實例,其中:

    • data屬性定義了所需的狀態變量:items存儲已加載的數據項,page記錄當前請求的頁碼,loadingMore表示是否正在加載更多,hasMore標識是否還有更多數據可加載。

    • mounted生命週期鉤子中,初始化時調用fetchData方法加載第一頁數據,並監聽窗口的scroll事件,綁定handleScroll方法處理滾動行爲。

    • beforeDestroy生命週期鉤子中,移除scroll事件監聽器,防止內存泄漏。

    • methods中定義了:

      • fetchData方法:負責發起Ajax請求,獲取下一頁數據。請求成功後,將新數據追加到items數組,並更新頁碼和loadingMore狀態。若本次加載數據不足15條,則設置hasMorefalse。若請求失敗,僅打印錯誤信息並恢復loadingMore狀態。

      • handleScroll方法:計算content-container距底部的距離distanceFromBottom。當距離小於等於閾值(100像素),且當前未處於加載狀態且仍有更多數據時,觸發fetchData方法加載更多數據。

使用div展示數據,通過Ajax動態加載,距離底部100像素時觸發加載,加載中顯示提示,加載失敗時不重試,每次加載15條數據。



歡迎關注公-衆-號【TaonyDaily】、留言、評論,一起學習。

公衆號

Don’t reinvent the wheel, library code is there to help.

文章來源:劉俊濤的博客


若有幫助到您,歡迎點贊、轉發、支持,您的支持是對我堅持最好的肯定(_)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章