用戶端篩選功能
簡介
這個範例示範如何實作用戶端篩選功能。
設定
此外,必須在標頭中匯入額外使用的 AMP 元件。我們使用 amp-bind
將產品在本機儲存到變數中。
<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
我們使用 amp-list
擷取靜態資料。
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
我們使用 amp-mustache
呈現資料。
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
用戶端篩選器
可以使用 amp-list
、amp-state
和 amp-bind
實作用戶端篩選功能。
amp-state
最初設定為來自端點的資料,該端點會傳回可用產品的清單;使用者可以選擇不同的顏色,而該選擇會將變數 filteredProducts
設定為篩選器運算式的結果。篩選器運算式是使用 Array.filter
函式的 amp-bind
運算式。
然後,filteredProducts
變數會用作 amp-list
的 src
。amp-list
不會自動調整大小,但可以使用 amp-bind
計算篩選狀態下的高度:在這裡,我們將 [height]
繫結至 filteredProducts
陣列的長度乘以單一元素的高度。
這種方法的替代方案是使用伺服器端篩選,我們在產品範例中說明了這一點。
<amp-state id="allProducts" src="/static/samples/json/related_products.json"></amp-state>
<select on="change:AMP.setState({
filteredProducts: allProducts.items.filter(a => event.value == 'all' ? true : a.color == event.value)
})">
<option value="all" selected>All</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="yellow">yellow</option>
<option value="orange">orange</option>
</select>
<amp-list height="282" [height]="(40 + 24) * filteredProducts.length" layout="fixed-height" src="/static/samples/json/related_products.json" [src]="filteredProducts" binding="no">
<template type="amp-mustache">
<amp-img src="{{img}}" layout="fixed" width="60" height="40" alt="{{name}}"></amp-img>
{{name}}
</template>
</amp-list>
需要更多說明嗎?
如果此頁面上的說明未涵蓋您的所有問題,請隨時與其他 AMP 使用者聯絡,討論您的確切使用案例。
前往 Stack Overflow 未說明的特色功能?AMP 專案大力鼓勵您的參與和貢獻!我們希望您成為我們開放原始碼社群的長期參與者,但我們也歡迎針對您特別感興趣的問題提供一次性貢獻。
在 GitHub 上編輯範例-
由 @sebastianbenz 撰寫