首页 > 解决方案 > VueJS + Firebase 如何显示图像?

问题描述

我想显示存储在 Firebase 中的图像,但它不起作用。目前,访问页面时不显示任何内容。错误在哪里?

[任务]

  1. 从 URL 获取 id (... /: id)
  2. 从 Firestore
      Document name = id获取图片 url
  3. 看图
<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>

标签: javascriptfirebasevue.jsgoogle-cloud-firestore

解决方案


以下应该有效:

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 中所解释的,因为“您使用的关键字functionthis在其范围内是匿名函数,而不是 vue 实例”。

通过使用箭头函数,您将解决错误。


另请参阅我对另一个答案所做的评论:通过调用异步get()方法,您将获得一个“使用DocumentSnapshot包含当前文档内容的 a 解析”的 Promise。在DocumentSnapshot您必须调用该data()方法以“将文档中的所有字段作为对象检索”。然后您必须分配其中一个字段的值,例如this.imageurl = doc.data().imageurl;


推荐阅读