javascript - VueJS + Firebase 如何显示图像?
问题描述
我想显示存储在 Firebase 中的图像,但它不起作用。目前,访问页面时不显示任何内容。错误在哪里?
[任务]
- 从 URL 获取 id (... /: id)
- 从 Firestore
Document name = id获取图片 url - 看图
<template>
<v-container>
<v-row align="center" justify="center">
<v-col cols="12" md="8" xs="12">
<img :src="imageurl" />
</v-col>
</v-row>
</v-container>
</template>
<script>
import firebase from "firebase";
var db = firebase.firestore();
export default {
data() {
return {
imageurl: ""
};
},
mounted() {
const id = this.$route.params.id;
let cityRef = db.collection("cards").doc(id);
let getDoc = cityRef.get();
this.imageurl = getDoc;
}
};
</script>
解决方案
以下应该有效:
mounted() {
const id = this.$route.params.id;
const cityRef = db.collection("cards").doc(id);
cityRef.get().then(doc => {
if (doc.exists) {
console.log(doc.data())
this.imageurl = doc.data().imageurl
} else {
console.log('no data')
}
})
.catch(error => {
//.....
}
}
正如Vue - Cannot set property of undefined in promise 中所解释的,因为“您使用的关键字function
,this
在其范围内是匿名函数,而不是 vue 实例”。
通过使用箭头函数,您将解决错误。
另请参阅我对另一个答案所做的评论:通过调用异步get()
方法,您将获得一个“使用DocumentSnapshot
包含当前文档内容的 a 解析”的 Promise。在DocumentSnapshot
您必须调用该data()
方法以“将文档中的所有字段作为对象检索”。然后您必须分配其中一个字段的值,例如this.imageurl = doc.data().imageurl;
推荐阅读
- tensorflow - 自定义反向传播
- react-native - 关于反应原生的 podfile 问题
- android - 如何确保为每个设备创建一个房间,而不是每次启动应用程序时创建一个新实例
- python - 聚合函数的分组和过滤
- mysql - 如何使用python访问位于不同位置(非本地)的另一台机器上的MySQL数据库
- angular - 使用 ngx-translate/core 进行角度翻译
- excel - 如何在多列中的公式中查找特定文本(基于列标题名称)并替换为不同的文本
- c# - 如何从一组源文件为多个框架编译 C# 代码
- php - 将 foreach 中的值连接到输入值属性中
- r - glmnet 和制作矩阵有问题吗?