因為是第一次用vantUI所以很多地方還不是很熟,這個vant-list列表加載數據又需要在很多地方用到,這里記一下正確的用法。。
這里先說一下會遇到的問題。
- 會無限請求接口
- 列表不會滾動始終只展示第一頁的數據
貼組件代碼
<template> <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> <van-list v-model="loading" :finished="finished" @load="onLoad" :offset="10" finished-text="沒有更多了" > <van-cell v-for="item in articlesList" :title="item.name_display"> <template #label> <van-image :src="timesrc" /> <span class="article-box-time">{{ item.name_display }}</span> </template> </van-cell> </van-list> </van-pull-refresh> </template>
這里就不作過多解釋,官方文檔對每個屬性都有解釋,這里我強調一下loading表示是否加載,finished表示是否加載完所有數據(一直請求接口的問題可能存在這里)
JS
data() { return { loading: false, //加載狀態 finished: false, //加載完成 refreshing: false, query: { currentPage: 1, pageSize: 10, }, articlesList: [], } },
這里有個問題,當loading設置為false時,首次加載的時候會觸發2次請求,但是設置為true后,頁面又無法向下滾動,這里暫時記一下這個問題。。
重點說一下加載代碼
首先在methods中獲取列表數據的方法
getList() { getArticlesList({ limit: this.query.pageSize, page: this.query.currentPage - 1, title: this.title, }) .then((msg) => { const rows = msg.list; if ( rows === null || rows.length === 0 || this.query.pageSize * this.query.currentPage > msg.meta.total ) { this.finished = true; } this.articlesList = this.articlesList.concat(rows); }) .finally(() => { this.refreshing = false; this.loading = false; }); },
這個getArticlesList是我請求后台的方法,也就是axios或ajax請求數據,title是篩選條件可以忽略。
mag.meta.total是后台返回的總條數。
這里就是說當當前頁數 x 每頁的總數 > 總記錄數 就表示所有數據已經加載完成就可以設置finished為true(之前一直通過其他形式來判斷的有問題,目前這種是最好的方法)
然后無論是否請求成功都需要將loading設置為false
然后onLoad中需要去加載這個方法,因為列表會向下滾動,所以注意這里要將頁數+1,也就是this.qurey.currentPage ++
onLoad() { this.query.currentPage++; this.getList(); },
然后在created中請求的是getList()而不是請求onLoad()方法,這里也要記一下。。
created() { this.getList() }
最后向下拉刷新的方法
//下拉刷新 onRefresh() { this.finished = false this.query.currentPage = 1 this.getList() },