[英]Polymer's two way data-binding not working in an element's child's attribute value
我有一個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
自定義元素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的開發人員工具進行檢查時,可以看到期望值反映在屬性上。 只是要添加,當我添加像這樣的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,該URL在迭代產品的數組時不會改變。 這將導致為所有產品加載相同的圖像,這不是理想的結果。
好問題。 現在,我也在努力地了解如何在光影dom內使用綁定。 如果找到解決方案,請確保將其發布在此處。
您可以將圖像插入從產品列表組件中移出,並移到產品卡元素中。 您並不是在靈活性方面尋求什么,但是您會獲得理想的效果。
<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和API中介紹了使用各種選擇器訪問lightdom的步驟。將ready函數添加到product-card元素中:
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"
},
...
嘗試使用src$="{{imageurl}}"
,因為這將綁定到src
屬性而不是src
屬性。
https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#attribute-binding
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.