I want to display an image stored in Firebase, but it doesn't work. Currently, nothing is displayed when accessing the page. Where are the mistakes?
[The task]
<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>
The following should work:
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".
By using an arrow function you will solve the error.
See also the comments I've made on the other answer: by calling the asynchronous get()
method you get a Promise that "resolves with a DocumentSnapshot
containing the current document contents". On the DocumentSnapshot
you have to call the data()
method to "retrieve all fields in the document as an Object". Then you have to assign the value of one of those fields, like this.imageurl = doc.data().imageurl;