Vant 的 List 組件 默認支持 瀑布流滾動加載。官方的示例是用定時器模擬的數據。我們在項目實戰中,肯定是結合ajax請求處理的。那么我們該如何實現這個效果呢?
Vant 的 List組件 使用方法這里就不詳細說明了,官方文檔已經寫的很詳細了。直接上項目中的實戰代碼:
<template> <div> <van-list v-model="loading" :finished="finished" :immediate-check="false" finished-text="沒有更多了" @load="onLoad" :offset="10" > //itemList換成你自己的數據 <van-cell v-for="item in itemList" :key="item.id"> </van-cell> </van-list> //沒數據時顯示 <div class="no-data" v-if="!this.itemList"> <img src="../assets/images/null.png" alt="暫無記錄" class="img" /> </div> </div> </template> <script> export default { created() { //創建組件時,加載第1頁數據 this.getroadList(); }, data() { return { loading: false, finished: false, page: 1,//請求第幾頁 pageSize: 10,//每頁請求的數量 total: 0,//總共的數據條數 itemList: [], }; }, methods: { getroadList() { let params = { page: this.page, pageSize: this.pageSize }; //this.$api.pay.schedule(params)是我自己封裝的get請求接口 this.$api.pay.schedule(params).then(res => { let rows = res.data.rows; //請求返回當頁的列表 this.loading = false; this.total = res.data.total; if (rows == null || rows.length === 0) { // 加載結束 this.finished = true; return; } // 將新數據與老數據進行合並 this.itemList = this.itemList.concat(rows); //如果列表數據條數>=總條數,不再觸發滾動加載 if (this.itemList.length >= this.total) { this.finished = true; } }); }, //滾動加載時觸發,list組件定義的方法 onLoad() { this.page++; this.getroadList(); } } }; </script>
注意事項:
設置<van-list>組件 :immediate-check="false"
理由:禁止 List 初始化時觸發 load 事件。把加載第一屏的事件放在 created() 里面。