我在聚合物中使用dom-repeat显示图像时遇到问题。我使用Firebase Storage来存储图像。
<firebase-query id="productsQuery"
data="{{products}}"
limit-to-first="2"></firebase-query>
上述元素的路径是动态更新的,运行正常。
<template is="dom-repeat" items="[[products]]" index-as="index">
<paper-card image="[[computePhotoURL(item.$key)]]" heading="[[item.name]]">
<div class="card-content">
<p class="shop-name">[[shopName]]</p>
<small>Php [[item.price]]</small>
</div>
</paper-card>
</template>
从上面的元素,一切都很好,他们显示信息,但与计算函数,它没有返回正确的url。
这是计算后的绑定代码:
computePhotoURL: function(key) {
var photo;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
photo = url;
return url;
}.bind(this)).catch( function(error) {
console.log('there was an error');
});
return photo;
}
通过记录上述函数的url,它显示了firebase存储的正确url,但似乎没有返回在纸卡的图像属性中绑定的正确值。
任何想法?提前谢谢你:)
我试着把它改成
computePhotoURL: function(key) {
var photo;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
photo = url;
console.log(photo);
//logs correct url
}.bind(this)).catch( function(error) {
console.log('there was an error');
});
console.log('photo', photo);
//logs undefined
return photo;
}
在正确的url之前先记录未定义。photo变量在被修改前返回。如何解决这个问题?JS不太好:(
对不起,我刚想起要张贴答案:
<template is="dom-repeat" items="[[products]]" index-as="index">
<paper-card id="card[[index]]" image="[[computePhotoURL(item.$key, index)]]" heading="[[item.name]]">
<div class="card-content">
<p class="shop-name">[[shopName]]</p>
<small>Php [[item.price]]</small>
</div>
</paper-card>
</template>
因此,正如您所看到的,我向计算绑定函数添加了一个索引参数,并为与索引连接的纸卡指定了一个ID,以区分其他的。
computePhotoURL: function(key, index) {
var id = '#card' + index;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
this.$$(id).image = url;
}.bind(this)).catch( function(error) {
console.log('there was an error', error);
});
}
因此,无论何时提取图像url,它都会根据dom-repeater使用this.$$(query):)生成的id引用图像属性
谢谢你的帮助,特别是@zerohero