最近剛結束了一個vue項目,項目中發現了自己很多問題,例如,看到功能就想要使用插件,(⊙o⊙)…,這樣是肯定不行呀,哎,用插件可以,自己也得會寫呀,現在就記錄一下一個不錯的滾動加載數據。
1.頁面布局(重點是 class="listWrapper" 以及 class="list")
<div class="listWrapper" ref="list_c"> <ul class="list" v-if="collectlist && collectlist.length>0" ref="list"> <li v-for="(item,index) of collectlist" :key="index"> <router-link :to="{name:'detail',query:{goods_sku_id:item.goods_sku_id}}"> <div class="picture"> <img :src="item.image"> </div> <div class="info-content"> <p class="pro-tit">{{item.name}}</p> <p class="price"> <span>¥{{item.price}}</span> <span class="old-price">¥{{item.ot_price}}</span> </p> <p class="count">已售{{item.sales_num}}件</p> </div> </router-link> <div class="collection-delete" @click="delect(item)"></div> </li> </ul> </div>
2.樣式
.listWrapper { position: absolute; top: 0.88rem; width: 100%; bottom: 0; overflow-y: auto; } .list { background-color: #fff; }
3.js
data數據
data() { return { page: 1, pagesize: 8, collectlist: [], canscroll: true, activeisload: true }; }
在mounted鈎子中添加監聽器(addEventListener)
mounted() { let list_c = this.$refs.list_c; list_c.addEventListener("scroll", () => { if (this.canscroll) { //是否具有觸發條件 let scroll_top = list_c.scrollTop; let list = this.$refs.list; let list_height = parseInt(getComputedStyle(list).height); let c_height = parseInt(getComputedStyle(list_c).height); if (list_height - (scroll_top + c_height) < 200) { this.canscroll = false; //鎖定滾動觸發條件 if (this.activeisload) { this.page++; this.getCollect(); } else { console.log("已加載完所有已收藏的商品"); } } } }); }
請求接口數據(this.$post是封裝的方法,自行代入實際場景)
getCollect: function() { this.$post(url, { page: this.page, pagesize: this.pagesize }) .then(res => { if (res.code == 200) { if (res.data.length) { this.collectlist = this.collectlist.concat(res.data); if (res.data.length < this.pagesize) { this.activeisload = false; console.log("已加載完"); } else { this.canscroll = true; } } } }) .catch(); },