作りたいもの
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を指定。