[英]Append data from firestore to an array in javascript
I'm playing with firebase right now, and I want to get display posts from the database.我现在正在玩 firebase,我想从数据库中获取显示帖子。 I've got an array of objects, but I don't know how to get the data into the array.我有一个对象数组,但我不知道如何将数据放入数组中。 This is my code:这是我的代码:
import * as firebase from "firebase/app";
import db from "@/plugins/firebase";
export default {
data() {
return {
posts: []
};
},
methods: {
get() {
db.collection("posts")
.get()
.then(snapshot => {
snapshot.forEach(doc => {
this.posts = doc.data();
console.log(this.posts);
});
})
.catch(err => {
console.log("Error getting documents", err);
});
}
}
};
Figured it out, turns out I had to create a new object and then use the spread operator.想通了,原来我必须创建一个新的 object 然后使用扩展运算符。
This is the working code:这是工作代码:
get() {
db.collection("posts")
.get()
.then(snapshot => {
let items;
snapshot.forEach(doc => {
this.posts.push({
...doc.data()
});
});
})
.catch(err => {
console.log("Error getting documents", err);
});
}
Try using尝试使用
.then(snapshot => {
snapshot.forEach(doc => {
this.posts.push(doc.data());
});
All you need is to use push() method so that the data coming from Firebase will get into the array defined above.您只需要使用 push() 方法,以便来自 Firebase 的数据将进入上面定义的数组。
If @shaykoo is getting the idea of your question right then you must use reactive variation of push()
method like this:如果@shaykoo 正确理解了您的问题,那么您必须使用push()
方法的反应变体,如下所示:
.then(snapshot => {
snapshot.forEach((doc,i)=> {
this.$set(this.posts, i, doc.data());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.