vue移動端實現滾動加載更多和下拉刷新功能,vant-ui的PullRefresh和List組件結合使用的坑

需求,移動端列表頁不再是分頁實現點擊上一頁下一頁,需要實現滾動到底部自動加載下一頁,頁面整個下拉的話,就刷新當前頁面的數據。

需求很簡單。我這邊引入了vant-ui,實現起來呢,遇到各種問題。網上找了一大圈,發現一個能打的都沒有,都有問題。我整個人都不好了。爲什麼呢?

特此先記錄一下,我的實現過程。雖然,不是最好的實現方式,但是,目前各種暴力測試,沒有發現bug了。總算能用了。

測試遇到的問題有哪些呢?下拉刷新,數據突然沒有了,頁面list空白;加載到第二頁,還在加載中,又暴力的進行下拉刷新,導致這個第二頁的數據,跑到第一頁的數據頂部,再後面又是第二頁數據,第三頁數據;不說了,測試了很多方法,都不行。這個破玩意,把我折騰的,實在是不輕。

目前的方法,比較穩定了,至少沒有這些莫名其妙的bug了。

    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="沒有更多了"
        @load="onLoad"
      >
        <div
          v-for="(item, index) in list"
          :key="index"
          class="item-wrap van-hairline--bottom"
        >
          <div class="item-name">{{ item.name }}</div>
        </div>
      </van-list>
    </van-pull-refresh>

。。。。。。。。。。
data() {
    return {
      list: [], // 列表數據
      pageIndex: 1, // 當前頁碼
      pageSize: 10, // 分頁大小
      total: 0, // 查詢總條數
      loading: false, // 滾動加載中
      finished: false, // 滾動加載完成
      isLoading: false, // 下拉強制刷新
    };
  },

list組件,監聽的方法是onLoad, 由loading和finished兩個來控制。
PullRefresh組件,由isLoading來控制,監聽的方法是onRefresh

分離出獲取數據ajax的函數,fetchList

// 獲取數據列表
    fetchList() {
      return new Promise((resolve, reject) => {
        let para = {
          data: {
            confirm: false,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
          },
        };
        temperatureWarningList(para)
          .then((res) => {
            let result = {
              total: res.data.recordTotal,
              pageIndex: res.data.pageIndex,
              list: res.data.list,
            };
            resolve(result);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

onLoad的內容

 // 滾動加載更多
    onLoad() {
      this.loading = true;
      this.fetchList().then((res) => {
        if (res.list.length < this.pageSize) {
          // 數據小於10條,已全部加載完畢finished設置爲true
          this.finished = true;
        }
        if (res.list.length === 0) {
          // 數據返回爲空,表示沒有數據了
          this.loading = false;
          this.finished = true;
        }
        // fix第二頁數據未加載完成就強制下拉刷新,導致上一次的第二頁的數據跑到這一次第一頁的數據的前面的bug
        if (this.pageIndex == res.pageIndex) {
          this.pageIndex = res.pageIndex + 1;
          this.list = this.list.concat(res.list);
        }
        this.loading = false;
      });
    },

onRefresh的內容

// 下拉刷新
    onRefresh() {
      this.list = [];
      this.pageIndex = 1;
      this.finished = false;
      this.loading = true;
      this.onLoad();
      this.isLoading = false; // 下拉加載完成,關閉,不然就會有兩個顯示加載中的轉圈圈。list本身就有一個了。啊。好惡心。
    },

如果您有更好的方法,還希望不吝賜教,請收下我的膝蓋。

時間緊,目前就這樣了。

未來,有更好的解決辦法了,再來更新。記錄一下。

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