Nuxt.js でFirebase にデータを保存する
前提
Firebase
側の設定を完了しておくこと。
Nuxt.js 側の設定
コード
<div class="form"> <input type="text" v-model="hoge"> <button @click="saveContent(hoge)">保存</button> </div> <script> import firebase from "~/plugins/firebase.js"; // △ https://blog-progblog-web.hatenablog.com/entry/2021/01/10/173554 の記事を参照 export default { data() { return { hoge: 'hello' }; }, methods: { logout: ()=> { firebase.auth().signOut(); }, saveContent: function(value) { var newNoteKey = firebase.database().ref().child('dids').push().key; firebase .database() .ref('dids/' + this.user.uid + '/' + newNoteKey) .push({content:value}); } } } </script>
解説
フロント(HTML)
<div class="form"> <input type="text" v-model="hoge"> <button @click="saveContent(hoge)">保存</button> </div>
input
タグで投稿の仕組みを作成する。
v-model=""
を使用しユーザーが入力する値をディレクティブに管理する。
最後に、クリック時にイベントを発火する。saveContent(hoge)
の hoge
は上記と同一になる。
仕組み(JavaScript)
最初にhoge: 'hello'
で hoge
の初期値を指定する。
次に肝心のクリック時の仕組みを作成する。
saveContent: function(value) {
value
はユーザーが入力したデータなので、hoge
と同一。
var newNoteKey = firebase.database().ref().child('dids').push().key; (中略……) .ref('dids/' + this.user.uid + '/' + newNoteKey)
上記は不要? 以下に変更する。
// var newNoteKey = firebase.database().ref().child('dids').push().key;
とりあえず理解できないので、コメントアウト。
firebase .database() .ref('dids/' + this.user.uid) .push({value}); }
firebase.database()
でデータを取り出す。
ref()
でdatabaseのURL指定を指定する?
つまり今回は、dids
> ユーザーID
となる。
.push({value});
で入力されたデータを保存する。
複数データを保存する
先にTODOリストを構築してまるっと保存する方が良さそうなので、別記事にて記載する。
コード
<div class="form"> <input type="text" v-model="hoge"> <input type="text" v-model="fugo"> <button @click="saveContent(hoge,fugo)">保存</button> </div> <script> import firebase from "~/plugins/firebase.js"; export default { data() { return { hoge: 'hello', fugo: 'goodbye' }; }, methods: { logout: ()=> { firebase.auth().signOut(); }, saveContent: function(hoge, fugo) { firebase .database() .ref('dids/' + this.user.uid) .push({hoge, fugo}); } } } </script> <style> </style>
で、いいのか。
現状これで、ふたつのアイテムを登録できたが、汎用性が悪いので、要検討。
先にTODOリストを構築してまるっと保存する方が良さそうなので、別記事にて記載する。