我正在尝试用聚合物制作购物车 而且我没有太多知识如何在模板中插入选定的数据 dom-repeat 到绑定到铁局部的数组 e.model.item 它不起作用。
<dom-module id="shop-cart">
<template>
<iron-ajax url="list.json" last-response="{{ListProducts}}" auto>
</iron-ajax>
<template is="dom-repeat" items="{{ListProducts}}">
<p style="display:block;width:400px">
<span>{{item.code}}</span>
<span>{{item.title}}</span>
<paper-button raised class="indigo" on-
click="addProduct">Add</paper-button>
<br/>
</p>
</template>
<iron-localstorage name="my-app-storage"
value="{{Orders}}"
on-iron-localstorage-load-empty="initializeDefaultOrders"
></iron-localstorage>
<template is="dom-repeat" items="Orders" as="order">
<div>
<p>{{order.code}}</p>
<p>{{order.title}}</p>
</div>
</template>
</template>
<script>
class ShopCart extends Polymer.Element {
static get is() {
return 'shop-cart';
}
static get properties() {
return {
Product: {
type: String
},
Orders: {
type: Array,
value() {
return [
{
code:'',
title:'',
}
];
},
},
ListProducts: {
type: Array,
value() {
return [];
},
}
}
}
initializeDefaultOrders() {
this.Orders = {
code:'',
title:''
}
};
addProduct(e) {
this.Product= e.model.item.title;
this.push('Orders',this.Product);
this.set('Product','');
}
deleteProduct(e) {
this.splice('Orders', e.model.index, 1);
}
}
window.customElements.define(ShopCart.is, ShopCart);
</script>
</dom-module>
<shop-cart></shop-cart>
传递给方法的值 addProduct(e( 与 ListProducts 项的数据模型无关。
下面是一个购物车示例,它将所选内容(正在选中的复选框(绑定到项的属性 item.selected。
https://github.com/renfeng/android-repository/blob/master/elements/android-sdk-manager.html#L267-L297
如果不需要复选框,您可以向按钮添加自定义属性。 例如,已选择
以下内容仅适用于聚合物 1。
<paper-button raised class="indigo" on-click="addProduct" selected="[[item.title]]">Add</paper-button>
并且,具有以下行以检索所选项目的标题。
this.Product= e.target.getAttribute("selected");
对于聚合物 2,这是您的修复方案。
https://github.com/renfeng/stackoverflow-question-44534326/commit/b2a4226bd5a1f5da7fa2d5a8819c53c65df7c412
已为聚合物 2 提出了自定义属性,但目前似乎未被接受。请参阅 https://github.com/Polymer/polymer/issues/4457