问题
I created the database on cloud firestore, and the collection name is products.
Now I want to retrieve all the resources in my collection. I have already created 12 products in my database. But in my vue-devtool, I cannot see any array.
How can I retrieve the data from cloud firestore?
Here is my vue.js code.
<template>
<h3 class="d-inline-block">Products list</h3>
<div class="product-test">
<div class="form-group">
<input type="text" placeholder="Product name" v-model="product.name" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="Price" v-model="product.price" class="form-control">
</div>
<div class="form-group">
<button @click="saveData" class="btn btn-primary">Save data</button>
</div>
<hr>
<h3>Product List</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products" :key="product">
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script>
import { fb, db } from '../firebase'
export default {
name: 'Products',
props: {
msg: String
},
data() {
return {
products: [],
product: {//object
name: null,
price: null
}
}
},
methods: {
saveData() {
// Add a new data in my table(It's done.).
db.collection("products").add(this.product)
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
this.product.name = "",
this.product.price = ""
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
},
//retrieve all the data from the database.
created() {
db.collection('products').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.products.push(doc.data());
});
});
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
回答1:
You can retrieve your products from the firestore collection in the mounted
of your vue file, and then push them into your products array using something like this:
<script>
import { db } from '../firebase';
export default {
data() {
return {
products: [],
};
},
mounted() {
db.collection('products').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.products.push(doc.data());
});
});
},
}
</script>
来源:https://stackoverflow.com/questions/62472002/vue-js-cannot-retrieve-data-from-cloud-firestore