我有一个 product-card
自定义元素,如下所示:
<dom-module id="product-card">
<template>
<div class="card-main-content layout horizontal center">
<content select="img"></content>
<content select="h3"></content>
<content select="h4"></content>
</div>
<content></content>
<paper-icon-button id="carticon" icon="add-shopping-cart" on-tap="cartTapped">
</paper-icon-button>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'product-card',
properties: {
host: {
type: String,
notify:true,
reflectToAttribute: true,
value: "http://localhost:3003"
},
imagepath: {
type: String,
notify: true,
reflectToAttribute: true
},
imageurl: {
type: String,
notify: true,
reflectToAttribute: true,
computed: 'computeImageUrl(host, imagepath)'
}
},
cartTapped: function(event) {
/*...............*/
this.fire('cart-tap');
},
computeImageUrl: function(host, imagepath) {
return host+imagepath;
}
});
})();
</script>
此元素在另一个名为 product-list
的自定义元素中使用,如下所示:
<dom-module id="product-list">
<template>
<get-products-service products="{{products}}" id="productservice"></get-products-service>
<div>
<template is="dom-repeat" items="{{products}}">
<product-card on-cart-tap="handleCart" imagepath="{{item.master.images.0.small_url}}">
<img src="{{imageurl}}" width="100" height="100">
<h3>{{item.name}}</h3>
<h4>{{item.display_price}}</h4>
</product-card>
</template>
</div>
</template>
</dom-module>
我遇到的问题是 src={{imageurl}}
解析为 null。 imageurl
正在计算,因为当我使用 chrome 的开发人员工具进行检查时,我可以看到预期值反射(reflect)在属性上。只是添加,当我添加这样的 imageurl
属性时:
<product-card on-cart-tap="handleCart" imagepath="{{item.master.images.0.small_url}}" imageurl="{{imageurl}}">
<img src="{{imageurl}}" width="100" height="100">
<h3>{{item.name}}</h3>
<h4>{{item.display_price}}</h4>
</product-card>
我得到第一个产品图片的 url,它不会随着产品数组的迭代而改变。这导致为所有产品加载相同的图像,这不是预期的结果。
最佳答案
好问题。现在我也在努力了解如何在 light dom 中使用绑定(bind)。如果我找到解决方案,我一定会在此处发布。
您可以将图像插入移出产品列表组件并移至产品卡片元素中。就灵 active 而言,这不是您想要的,但您会获得预期的效果。
<dom-module id="product-card">
<template>
<div class="card-main-content layout horizontal center">
<img src="{{imageurl}}" width="100" height="100">
<content select="h3"></content>
<content select="h4"></content>
</div>
<content></content>
<paper-icon-button id="carticon" icon="add-shopping-cart" on-tap="cartTapped">
</paper-icon-button>
</template>
</dom-module>
另一种获得所需结果的“hacky”方法是在生命周期的就绪回调中设置图像 src。使用 Polymer.dom(this).querySelector('img')
访问 lightdom 内的图像元素并设置计算值的 src。 Local DOM Basics and API 中描述了使用各种选择器访问 lightdom。将就绪功能添加到您的产品卡片元素:
Polymer({
is: 'product-card',
ready: function() {
Polymer.dom(this).querySelector('img').src = this.imageurl;
},
properties: {
host: {
type: String,
notify:true,
reflectToAttribute: true,
value: "http://lorempixel.com/50/50"
},
...
关于javascript - polymer 的双向数据绑定(bind)在元素的子属性值中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687952/