小程式瀑布流元件實現翻頁與圖片懶載入
電商小程式中,用到瀑布流的地方非常多,每次都寫一個瀑布流,重複一次邏輯,作為程式設計師,肯定是非常不願意的。
瀑布流的形式都是大同小異,不同的是瀑布流中每個模組的內容,隨業務而變化。
所以,我們把瀑布流框架抽象成元件,瀑布流的內容由業務確定。這樣即可實現元件化和自定義的最大平衡,微信小程式元件原始碼。
首先,我們來看一下瀑布流元件在實際專案中的實際效果。
1 實際效果
瀑布流元件實際效果如下圖所示,左側為使用者互動效果,右側為圖片懶載入實際效果。
2 什麼是瀑布流?
瀑布流,又稱瀑布流式佈局。是比較流行的一種網站頁面佈局,waterfall-item
寬度固定,高度不定,視覺表現為參差不齊的多欄佈局,隨著頁面滾動條向下滾動,這種佈局還會不斷載入資料塊並附加至當前尾部。如下圖所示:
3 實現功能
該瀑布流元件實現了以下幾個功能:
- 支援圖片懶載入
- 支援上拉資料翻頁
- 支援自定義樣式
- 支援瀑布流Item間隔底層自動計算
- 原生元件模式:即類swiper和swiper-item 元件用法
- 元件與資料完全解耦
4 實現原理
4.1 waterfall 和waterfall-item實現原理
第一步:在 waterfall-layout 目錄下建立 waterfall
和 waterfall-item
元件,目錄結構如下:
. ├── query-node.js ├── waterfall-item.js ├── waterfall-item.json ├── waterfall-item.wxml ├── waterfall-item.wxss ├── waterfall.js ├── waterfall.json ├── waterfall.wxml └── waterfall.wxss
第二步:分別在waterfall.js
和 waterfall-item.js
的relations
選項中指定元件父、子級關係:
// waterfall.js Component({ // ... other code relations: { './waterfall-item': { type: 'child',},// ... other code } })
// waterfall-item.js Component({ // ... other code relations: { '././waterfall': { type: 'parent',// ... other code } })
指定彼此的父、子元件的關係後,即可通過 this.getRelationNodes
原生 API,就能訪問彼此例項物件及其屬性和方法。
第三步:實現waterfall.wxml
和 waterfall-item.wxml
程式碼:
waterfall.wxml
程式碼實現非常簡單,只有5行程式碼:
<view class="waterfall custom-class"> <view class="waterfall-inner"> <slot ></slot> </view> </view>
同樣,waterfall-item.wxml
程式碼實現也非常簡單,只有5行程式碼:
<view class="waterfall-item custom-class" style="{{position}}:0;top:{{(top >= 0 ? top + 'px' : 0 + 'rpx')}};" > <slot ></slot> </view>
不知道slot
用法的童鞋,請參考微信小程式自定義元件模板和樣式文件。
4.2 瀑布流原理
其實,不管是微信小程式、web、還是原生APP,瀑布流的實現原理都是一樣的。都可以絕對定位和位置計算來實現。
瀑布流的大體過程如下圖所示:
第一步:資料通過this.setData
從邏輯層傳輸到檢視層,進行第一渲染,由於每個waterfall-item
的top:0;
和 position:left;
,所以都重疊了在一起。
第二步:通過節點查詢API獲取每個waterfall-item
元素資訊,並且計算出正確的top
和position
值。
第三步:setData
每個waterfall-item
的top
和position
,實現重排。
具體邏輯實現如下:
首先,我們來實現一個節點查詢API querySelector
,之後會用到:
// query-node.js /** * 獲取當前頁面中,選擇器為 selector 的第一個node節點 * @param {String} selector 符合微信小程式規範的選擇器 * @param {Object} context 呼叫環境,普通頁面中為wx,自定義元件中為this;預設值為wx. * @return {Array} 返回一個數組,第一個元素為 node 節點 */ export const querySelector = function (selector,context = wx) { return new Promise((resolve,reject) => { context.createSelectorQuery() .select(selector) .boundingClientRect((res) => { if (res) { resolve(res); } else { reject(`不存在選擇器為 ${selector} 的節點`); } }) .exec(); }) };
接著,看一下元件waterfall
和waterfall-item
在實際專案中的用法:
<waterfall loading="{{loadMorePending}}" isAllLoaded="{{isAllLoaded}}" > <block wx:for="{{data.sections}}" wx:key="id" wx:for-item="product"> <waterfall-item index="{{index}}" custom-class="flow-item-wrapper" > <view class="product-item"> 業務程式碼 </view> </waterfall-item> </block> </waterfall>
當第一個waterfall-item
元件,在檢視層佈局完成後會執行ready
生命週期鉤子。
在 ready
生命週期鉤子中,我們需要做兩件事:
- 獲取父元件
waterfall
的例項物件,並掛載在waterfall-item
元件的this
例項物件上。因為之後我們需要在waterfall-item
元件中修改waterfall
上的資料。 - 獲取
waterfall-item
元件的高度,計算waterfall-item
元件的位置資訊top
和position
。
// waterfall-item.js import { querySelector } from './query-node'; Component({ // ... other code lifetimes: { ready() { const [waterfall] = this.getRelationNodes('./waterfall'); this.parent = waterfall; this.setWaterfallItemPosition(); },} methods:{ async setWaterfallItemPosition() { querySelector('.waterfall-item',this) .then(async (node) => { const { top,position } = await this.parent.getWaterfallItemPostionInfo(node); this.setData({ top,position }) }) },} // ... other code })
在setWaterfallItemPosition
方法中,我們呼叫了父元件上的方法this.parent.getWaterfallItemPostionInfo
,獲取當前waterfall-item
元件的top
和position
資訊。並把已經渲染好的waterfall-item
元件的累計高度快取在waterfall
的leftHeights
和rightHeights
屬性上,用於計算下一個waterfall-item
元件位置,主要邏輯如下:
// waterfall.js const POSITION_LEFT = 'left'; const POSITION_RIGHT = 'right'; Component({ // ... other code /** * 元件的方法列表 */ methods: { lifetimes: { ready() { this.initParams(); } },initParams() { this.leftHeights = 0; this.rightHeights = 0; },/** * 設定 waterfall-item 的高度值 * @param {Object} node waterfall-item 元件位置尺寸資料 */ async getWaterfallItemPostionInfo(node) { let top = 0; let position = POSITION_LEFT; const { height } = node; const { itemGap } = this; if (this.leftHeights <= this.rightHeights) { top = this.leftHeights; if(this.leftHeights === 0) { this.leftHeights += height; } else { top += itemGap; this.leftHeights += (height + itemGap); } } else { position = POSITION_RIGHT; top = this.rightHeights; if(this.rightHeights === 0) { this.rightHeights += height; } else { top += itemGap; this.rightHeights += (height + itemGap); } } return { top,position,} } // ... other code } })
當所有的waterfall-item
重排結束後,瀑布流渲染完成。
4.3 圖片懶載入原理
微信小程式中,<image>
標籤本身是支援懶載入的,當lazy-load={{true}}
,且在即將進入一定範圍(上下三屏)時才開始載入。
也就是說,當lazy-load={{true}}
,<image>
標籤初次渲染在視口上下三屏之外時,是不會請求圖片資源的,當<image>
即將進入三屏之內時,才會載入。
在4.2小節的圖3中,<waterfall-item>
的初始化位置設定成了top:0;
和 position:left;
,所以,都在視口中。如果將top
的值成三屏之外的數值,例如,400vh
或者更大,則<waterfall-item>
重排之後,任然在三屏之外的圖片即會自動懶載入。
<view class="waterfall-item custom-class" style="{{position}}:0;top:{{(top >= 0 ? top + 'px' : itemCount * 100 + 'vh')}};" > <slot ></slot> </view>
Component({ // waterfall-item.js // ... other code lifetimes: { ready() { const { itemCount } = this.data; const [waterfall] = this.getRelationNodes('./waterfall'); waterfall.childCount += 1; this.parent = waterfall; this.setData({ itemCount: itemCount + waterfall.childCount,}) },// ... other code })
4.4 資料翻頁
因為實現了wx:for
<waterfall-item>
功能,和<swiper-item>
元件一樣,因此翻頁邏輯完全由使用者自己定製,<waterfall>
和<waterfall-item>
只給你提供翻頁的功能,元件就可以和瀑布流資料結構完全解耦。
4.5 瀑布流Item間隔底層自動計算
將列和行中,兩個<waterfall-item>
元件之間的距離定義為itemGap
,則:
itemGap = waterfall寬度 - (waterfall-item寬度 * 2)
在<waterfall>
的ready
鉤子中,可以獲取到<waterfall>
元件的寬度;同理,在<waterfall-item>
的ready
鉤子中,可以獲取到<waterfall-item>
元件的寬度。
在呼叫getWaterfallItemPostionInfo
之前,獲取到itemGap
的值即可。這樣,在計算<waterfall-item>
的top
值時,除了第一行的<waterfall-item>
的top
值等於0之外,其他所有<waterfall-item>
的top
值等於:
// this.leftHeights += height + itemGap; // or // this.rightHeights += height + itemGap;
具體程式碼實現請檢視原始碼
5 總結
通過瀑布流框架抽象,使<waterfall>
和<waterfall-item>
接近原生元件使用體驗,同時使元件與資料完全解耦。通過巧妙的初始化位置top
設定,使瀑布流具圖片有懶載入的功能。
到此這篇關於小程式瀑布流元件實現翻頁與圖片懶載入的文章就介紹到這了,更多相關小程式瀑布流內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!