post.vue
<button class="btn" @click.prevent="postItem">投稿</button>
<script>
methods: {
postItem() {
firebase
.firestore()
.collection("posts")
.add({
title: this.title,
description: this.description,
image: this.image,
genre: this.genre,
time: firebase.firestore.FieldValue.serverTimestamp()
})
.then(() => {
confirm("投稿しますか?");
});
}
}
};
</script>
postItem()が押下されたら、dbインスタンスを初期化して"posts"という名前のコレクションを参照し、add()でそれぞれのデータを格納する。
time: firebase.firestore.FieldValue.serverTimestamp()
作成・編集時刻につきましては、自動で取得してくれる便利なものがありますので、そちらを使用してます。
◇参考 Firestoreでドキュメントの作成/編集時刻をサーバ側に任せる方法
.then(() => {
confirm("投稿しますか?");
});
上記で確認ダイアログを表示させています。
mounted() {
this.db = firebase.firestore().collection("posts");
},
※何度も使う場合は、リファクタリングで関数で定義しておくとGOOD!!
board.vue / 親コンポーネント
<List v-for="(list,index) in allData" :index="index" :list="list" :key="list.id" />
allDataのデータをlistとindexにそれぞれ格納。
v-for="(list,index) in allData" / v-for="(値, キー) in 配列orオブジェクト" では、下記のようなイメージ。
allData1
0.title ~
1.genre ~
2.image ~
3.time ~
4.description ~
allData2
0.title ~
1.genre ~
2.image ~
3.time ~
4.description ~
:index="index" / v-bind:属性名="値"では、下記のようなイメージ。
list: [title.genre.image.time.description]
index: [0.1.2.3.4]
<script>
export default {
data() {
return {
allData: []
};
},
created() {
firebase
.firestore()
.collection("posts")
.get()
.then(snapshot => {
//"posts"(参照先)のスナップショットを得る
snapshot.forEach(doc => {
//上記で得たデータをforEachでドキュメントの数だけ"doc"データに格納
this.allData.push(doc.data());
//更にallDataの空箱に格納した"doc"データを格納
});
});
}
};
</script>
"posts"コレクションの全ドキュメントを取得し、get()でdoc"データに格納後、push()でallDataに格納してます。
list.vue / 子コンポーネント
<a href="#" class="small-font">{{user.name}}</a>
</div>
<div class="list-ttl">{{list.title}}</div>
<div class="post-container">
<p>{{list.description}}</p>
</div>
<div class="post-genre">{{list.genre}}</div>
<div class="btn-inner">
<button class="btn">ルームへ参加</button>
propsを使って親コンポーネントから値を取得したデータがlist内にデータが格納させているので、{{}}を使用してlist内のそれぞれの値を取得。
<script>
props: {
list: {
type: Object
//propsにより親コンポーネントから受け取ったデータをlist内にObject型で格納されてる
},
index: {
type: Number
//propsにより親コンポーネントから受け取ったデータをindex内にNumber型で格納されてる
}
}
</script>
親コンポーネントから取得したデータが下記になります。
list: [title.genre.image.time.description]
index: [0.1.2.3.4]
◇参考 Vueのpropsの使い方