2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nuxt+firestoreで投稿、投稿一覧作成

Last updated at Posted at 2019-10-13

作りたいもの

nuxt+firestoreで投稿、投稿一覧を作成。

  • firestoreに投稿
  • firestoreの投稿を参照してリストレンダリング
  • 投稿の詳細ページへのリンク作成

firestoreに投稿

<script>
methods: {
    makeroom: function () {
      var db = firebase.firestore()
      db.collection('room').doc('部屋').set({
        room_title: 'room_title',
        user_id: this.$store.state.uid
      })
      .then(function (docRef) {
        console.log('Document written with ID: ', docRef.id)
      })
      .catch(function (error) {
        console.error('Error adding document: ', error)
      })
    }
  }
</script>

methodsでmakeroomを定義して@clickで発火させる。

firestoreの投稿を参照してリストレンダリング

export default {
  name: 'postsindex',
  data: function () {
    return {
      posts: []
    }
  },
  created() {
    const db = firebase.firestore()
    db.collection('room').get().then(querySnapshot => {
      querySnapshot.forEach(doc => {
        this.posts.push({
          ...doc.data(),
          id: doc.id
        })
      })
    })
  }
}
  • getで取得した配列をquerySnapshotに
  • そのquerySnapshotをforEachでまわす
  • docに一つひとつ格納し、doc.dataをスプレッド演算子で展開
  • それにidを追加してまとめた状態にしてpush、postsに格納していく

スプレッド演算子で展開しつつ、idを足すのはここを見た

投稿の詳細ページへのリンク作成

<nuxt-link :to="{ name: 'rooms-id', params: { id: post.id } }">

router.jsでnameを確認して指定する。paramsのidを指定。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?