簡體   English   中英

VueJS + Firebase 如何顯示圖像?

[英]VueJS + Firebase How do I display an image?

我想顯示存儲在 Firebase 中的圖像,但它不起作用。 目前,訪問頁面時不顯示任何內容。 錯誤在哪里?

[任務]

  1. 從 URL 獲取 id (... /: id)
  2. 從 Firestore 獲取圖像 url
    文檔名稱 = id
  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>

以下應該有效:

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 => {
        //.....
    }
}

As explained in Vue - Cannot set property of undefined in promise , since "you are using the keyword function , this is inside its scope the anonymous function, not the vue instance".

通過使用箭頭 function 您將解決錯誤。


另請參閱我對另一個答案所做的評論:通過調用異步get()方法,您將獲得一個 Promise ,它“使用包含當前文檔內容的DocumentSnapshot解析”。 DocumentSnapshot上,您必須調用data()方法來“將文檔中的所有字段作為對象檢索”。 然后您必須分配其中一個字段的值,例如this.imageurl = doc.data().imageurl;

cityRef.get()返回一個 promise,所以你應該這樣得到圖像:

cityRef.get().then(function(doc) {
 if (doc) {
  console.log(doc.data()) // doc.data() is a response from your query
  this.imageurl = doc.data().imageurl
 } else {
  console.log('no data')
 }
} catch(error) {
...
}

那里有 文檔

您需要更改語法以加載 firebase 並獲取文檔:

import firebase from 'firebase/app'
import firebaseConfig from './config/firebase' .  // Your firebase config init settings.
...

db.collection('cards').doc(id)
.get().then(docSnapshot => {
    if (!docSnapshot.exists) return;
    let data = docSnapshot.data()
    // continue your code
});

PS:我看到你使用新的 Vuetify 2,太棒了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM