1. 程式人生 > 其它 >上拉載入更多(vant元件庫)

上拉載入更多(vant元件庫)

1.定義data變數值

  data() {
return {
page: 1,
limit: 10,
artlist: [],
// 是否正在載入下一頁資料,改為true則不會反覆觸發load事件
// 每當下一頁資料請求回來之後,千萬記得把loading從true改為false
loading: true,
// 所有資料是否載入完畢,如果沒有下一頁資料了應改為true
finished: false,
};
},

2.在載入的元件外包裹

loading為true不會觸發@load事件,為false觸發

 <van-list
v-model="loading"
:finished="finished"
finished-text="沒有更多了"
@load="onload"
>
<ArticleInfo
v-for="item in artlist"
:key="item.id"
:title="item.title"
:author="item.aut_name"
:time="item.pubdate"
:count="item.comm_count"
:cover="item.cover"
></ArticleInfo>
</van-list>

3.定義load事件

呼叫load事件page頁碼+1,再呼叫資料請求,此時請求的頁碼資料+1

  methods: {
onload() {
console.log("觸發了load事件");
this.page++;
this.initArticleList();
},
},

4.initArticleList方法

當請求到新資料後需要覆蓋到artlist資料中,使用解構賦值

// this.artlist = [舊資料在前,新資料在後]

判斷當請求的資料為0時 finished值改為true,結束載入,

在每一次重新整理後將loading改為false觸發@load方法。

  methods: {
async initArticleList() {
const { data: res } = await getArticleListAPI(this.page, this.limit);
console.log(res);
// 上拉載入更多 應該是
// this.artlist = [舊資料在前,新資料在後]
this.artlist = [...this.artlist, ...res];
// 當請求的值沒有資料了,就將資料載入finshed改為true
if (res.length == 0) {
this.finished = true;
}
this.loading = false;
},

},