AMP
  • 網站

用戶端篩選器

簡介

這是一個示範如何實作用戶端篩選器的範例。

設定

此外,必須在標頭中匯入使用的 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-listamp-stateamp-bind 來實作用戶端篩選器。

amp-state 最初設定為來自端點的資料,該端點傳回可用產品的清單;使用者可以在不同的顏色之間選擇,並且該選擇將變數 filteredProducts 設定為篩選運算式的結果。篩選運算式是一個 amp-bind 運算式,它使用 Array.filter 函式。

然後,filteredProducts 變數用作 amp-listsrcamp-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 上編輯範例