如何在Firestore中创建一个数组?

时间:2018-08-07 21:01:44

标签: javascript firebase vue.js google-cloud-firestore

我需要在Firebase Firestore中创建哪个代码?

我要存储userDetails

  userName: this.userProfile.name,
  userImage: this.userProfile.image,
  userId: this.userProfile.userId

作为Firestore

中的数组

Vue组件:

...
data () {
 return {
     postDetails: {
      createdOn: new Date(),
      content: '',
      userId: null,
      image: null,
      comments: 0,
      likes: 0,
      userDetails: []
    }
    userData: [
     { userName: this.userProfile.name },
     { userImage: this.userProfile.image},
     { userId: this.userProfile.userId }
 }
},
methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: this.userData
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}

End result should look likes this one

1 个答案:

答案 0 :(得分:1)

我看到您正在改写Firestore和Vue.js教程中的代码:https://savvyapps.com/blog/definitive-guide-building-web-app-vuejs-firebase

实际上,在本教程中,userProfile数据来自vue商店,

  computed: {
    ...mapState(['userProfile', 'currentUser', 'posts'])
  },

您的问题中缺少这部分代码,但很可能是造成问题的原因:在您的Vue.js组件中,您尝试在数据中使用计算属性,但是“由于组件创建时机的原因,这是不可能的” :数据先计算计算出的属性”。

请参见Use computed property in data in Vuejshttps://forum.vuejs.org/t/computed-properties-in-data/11231

只需按如下所示直接访问计算的属性,它将起作用:userData将存储为数组。

methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: [
        { userName: this.userProfile.name },
        { userImage: this.userProfile.image},
        { userId: this.userProfile.userId }
      ]
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}