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 设置为筛选表达式的结果。筛选表达式是使用 Array.filter 函数的 amp-bind 表达式。

然后,将 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 上编辑示例