因此,我正在尝试从我的 firebase 存储中检索某些 pdf 的链接。当我获得链接时,我想将它们绑定(bind)到某些列表。问题是在获取链接之前加载了模板,因此列表的 href 属性保持为空。我也在使用 Vuetify。
这是我的模板
<template>
<v-layout row wrap v-if="count > 0">
<v-flex v-for="n in count" :key="n">
<v-card:href="link[n-1]" target="_blank">
<v-icon>mdi-file-pdf</v-icon>
<span>Module {{n}}</span>
</v-card>
</v-flex>
</v-layout>
这是我的脚本
<script>
import firebaseApp from "@/firebase/init.js";
var storage = firebaseApp.storage();
var storageRef = storage.ref();
export default {
name: "Dashboard",
data() {
return {
id: this.$route.params.id,
count: null,
link: [],
loading: null
};
},
methods: {
getFile() {
this.link = [];
this.loading = true;
var listRef = storageRef.child(`folder_name${this.id}`);
listRef.listAll().then(res => {
this.count = res.items.length;
for (let i = 1; i <= this.count; i++) {
var starsRef = storageRef.child(`folder_name${this.id}/file_name${i}.pdf`);
starsRef.getDownloadURL().then(url => {
this.link[i - 1] = url;
});
}
this.loading = false;
});
},
updateId() {
this.id = this.$route.params.id;
this.getFile();
}
},
created() {
this.getFile();
},
watch: {
$route: "updateId"
}
};
</script>
链接数组最终会存储所有的链接。但它不会绑定(bind)到 span 标签 我如何在不使用 vuex 的情况下解决这个问题? 提前致谢
最佳答案
getDownloadURL()
方法是异步的并返回一个 Promise。由于您想对 storageRef.child('folder_name${this.id}')
中的所有文件并行执行此方法,因此您应该使用 Promise.all()
在更新 link
数组之前等待所有异步操作完成。
以下,使用forEach()
而不是 for
循环,应该可以解决问题(未经测试):
listRef.listAll()
.then(res => {
const promises = [];
res.items.forEach(itemRef => { //items is an array of Reference
promises.push(itemRef.getDownloadURL());
});
return Promise.all(promises);
.then(urls => {
this.link = urls;
});
然后,在你的组件中你会做:
<v-layout row wrap v-if="count > 0">
<v-flex v-for="(item, index) in link">
<v-card :href="item" target="_blank">
<v-icon>mdi-file-pdf</v-icon>
<span>Module {{index + 1}}</span>
</v-card>
</v-flex>
</v-layout>
关于javascript - Vue.js:如何在我从 firebase 存储中检索数据后异步加载模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59858569/