我将图像的相对路径存储在我希望显示的每个项目的防火墙数据库中。当我需要异步获取图像时,我很难将图像显示在屏幕上。当前的火基模式如下:
{
items: {
<id#1>: {
image_loc: ...,
},
<id#2>: {
image_loc: ...,
},
}
}我希望在我的页面上显示这些图像中的每一个,代码如下:
<div v-for="item in items">
<img v-bind:src="item.image_loc">
</div>这是不工作的,因为我的相对位置指向一个地方在火场存储。从这个相对url获取真正url的相关代码是:
firebase.storage().ref('items').child(<the_image_loc>).getDownloadURL()它用真实的url返回一个承诺。下面是我当前的vue.js代码:
var vue = new Vue({
el: '.barba-container',
data: {
items: []
},
firebase: function() {
return {
items: firebase.database().ref().child('items'),
};
}
});我尝试过使用计算属性,包括使用vue-异步计算,但这些解决方案似乎无法工作,因为我不能传递参数。
基本上,如何显示每个元素都需要承诺结果的元素列表?
发布于 2017-05-18 15:29:45
我能够解决这个问题,方法是使用asyncComputed库实现vue.js,并承诺一次下载所有图像,而不是单独下载。
/**
* Returns a promise that resolves when an item has all async properties set
*/
function VotingItem(item) {
var promise = new Promise(function(resolve, reject) {
item.short_description = item.description.slice(0, 140).concat('...');
if (item.image_loc === undefined) {
resolve(item);
}
firebase.storage().ref("items").child(item.image_loc).getDownloadURL()
.then(function(url) {
item.image_url = url;
resolve(item);
})
.catch(function(error) {
item.image_url = "https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
resolve(item);
});
});
return promise;
}
var vue = new Vue({
el: '.barba-container',
data: {
items: [],
is_loading: false
},
firebase: function() {
return {
items: firebase.database().ref().child('items'),
};
},
asyncComputed: {
processedItems: {
get: function() {
var promises = this.items.map(VotingItem);
return Promise.all(promises);
},
default: []
}
}
});最后,我需要在模板中使用:v-for="item in processedItems"来呈现带有图像urls的项目。
发布于 2018-02-24 21:33:33
在解析url之前,我能够在没有任何额外依赖项的情况下解决它,不向数组添加元素:
在我的模板中:
<div v-for="foo in foos" :key="foo.bar">
<img :src="foo.src" :alt="foo.anotherbar">
...
</div>在我的组件中(例如在mounted()内部)
const db = firebase.firestore()
const storage = firebase.storage().ref()
const _this = this
db.collection('foos').get().then((querySnapshot) => {
const foos = []
querySnapshot.forEach((doc) => {
foos.push(doc.data())
})
return Promise.all(foos.map(foo => {
return storage.child(foo.imagePath).getDownloadURL().then(url => {
foo.src = url
_this.foos.push(foo)
})
}))
}).then(() => {
console.log('all loaded')
})https://stackoverflow.com/questions/44037495
复制相似问题