實現移動端上拉載入和下拉重新整理的vue外掛(mescroll.js)
阿新 • • 發佈:2018-12-09
做一個簡單的移動端展示專案,後臺分頁後前端載入,實現上拉載入下一頁,找了下,還是用這個mescroll.js外掛好一點
1.npm安裝
npm install --save mescroll.js //不要使用cnpm安裝
- 匯入(在哪個頁面使用,則在哪個頁面匯入(這裡的話,我使用全域性匯入會出現問題,若有錯,還請大家指出,暫時想到的就是區域性引入)):
import MescrollVue from ‘mescroll.js/mescroll.vue’
- 註冊元件:
components: {
MescrollVue // 註冊mescroll元件
},
- template使用
<mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit" class="scrollView"></mescroll-vue>
2.data裡進行相關配置
data () { return { mescroll: null, // mescroll例項物件 mescrollDown:{}, //下拉重新整理的配置. (如果下拉重新整理和上拉載入處理的邏輯是一樣的,則mescrollDown可不用寫了) mescrollUp: { // 上拉載入的配置. callback: this.upCallback, // 上拉回調,此處簡寫; 相當於 callback: function(page, mescroll) { } //以下是一些常用的配置,當然不寫也可以的. page: { num: 0, //當前頁 預設0,回撥之前會加1; 即callback(page)會從1開始 size: 10 //每頁資料條數,預設10 }, noMoreSize: 5, //如果列表已無資料,可設定列表的總數量要大於5才顯示無更多資料;避免列表資料過少(比如只有一條資料),顯示無更多資料會不好看 toTop: { //回到頂部按鈕 src: "./static/mescroll/mescroll-totop.png", //圖片路徑,預設null,支援網路圖 offset: 1000 //列表滾動1000px才顯示回到頂部按鈕 }, htmlContent: '<p class="downwarp-progress"></p><p class="downwarp-tip">下拉重新整理 </p>', //佈局內容 empty: { //列表第一頁無任何資料時,顯示的空提示佈局; 需配置warpId才顯示 warpId: "xxid", //父佈局的id (1.3.5版本支援傳入dom元素) icon: "./static/mescroll/mescroll-empty.png", //圖示,預設null,支援網路圖 tip: "暫無相關資料~" //提示 } }, articleList: [] // 列表資料 } }, beforeRouteEnter (to, from, next) { // 如果沒有配置回到頂部按鈕或isBounce,則beforeRouteEnter不用寫 next(vm => { vm.$refs.mescroll.beforeRouteEnter() // 進入路由時,滾動到原來的列表位置,恢復回到頂部按鈕和isBounce的配置 }) }, beforeRouteLeave (to, from, next) { // 如果沒有配置回到頂部按鈕或isBounce,則beforeRouteLeave不用寫 this.$refs.mescroll.beforeRouteLeave() // 退出路由時,記錄列表滾動的位置,隱藏回到頂部按鈕和isBounce的配置 next() }, methods: { mescrollInit(mescroll) { this.mescroll = mescroll; }, upCallback(page, mescroll) { this.$Request({ url: "", method: "get", data: { page: page.num }, success: res => { if (res.status == 1) { let data = page.num == 1 ? [] : this.articleList; data.push(...res.result.data); this.articleList = data; // 資料渲染成功後,隱藏下拉重新整理的狀態 this.$nextTick(() => { mescroll.endSuccess(res.result.data.length); }); } } }); } } }
3.style樣式
style
.mescroll {
position: fixed;
padding-bottom: 1rem;
top: 2px;
bottom: 0;
height: auto;
}
4.載入完成後
- 可以在data中的mescrollUp項中進行底部沒有更多資料時的提示資訊,'END'及'載入中...'這些內容可以自己設定
htmlLoading: '<p class="upwarp-progress mescroll-rotate"></p><p class="upwarp-tip">載入中..</p>', //上拉載入中的佈局 htmlNodata: '<p class="upwarp-nodata">-- END --</p>', //無資料的佈局
5.scroll屬性在ios手機上回出現卡頓問題
- 在進行滾動的這個容器樣式中新增這個屬性:
-webkit-overflow-scrolling:touch;
- 但是的話,填加了這個相容會導致定位為position:fixed的失去效果,看了一些資料,使用position:absolute可以解決,這個我沒有具體的再去實驗下,若有好的方法,還請大家能夠在評論裡告知下,感激不盡
正在努力學習中,若對你的學習有幫助,留下你的印記唄(點個贊咯^_^)