前置き
便利なfirebase!
シンプルに導入の仕方を解説していきます😉
簡単なデータの書き込みと取得をしてみます🍒
firebaseとは
簡単に言うと
オンラインにデータを保存できて
取得もできる優れものです!
自分で1から作るとなると大変ですが
firebaseを使えば簡単ですね🌟
Firebase Realtime Database
どんな時に使うか?
ex1) チャットアプリ
リアルタイムにデータを保存・同期できるので
メッセージを送り合うことが簡単になります💌
ex2) フリマサイト!👕👖
会員情報とその会員が出品した商品が
DBに保存されていきます。
それを会員はいつでも編集でき、
反映したらすぐ表示が変わるわけです💡
会員自身でデータが作れて編集もできる!
といった感じです🌟
Referenceの読み方
基本的にfirebaseのreferenceは
英語の状態で表示し、
自分でgoogle翻訳で翻訳しましょう📚🔍
言語を日本語にすると
古いバージョンだったりするので、
最新の英語を翻訳していくのがベスト!⭕️
ただいきなり全部英語だと
欲しい情報がどこにあるか分からないので
最初は日本語で表示させて
ある程度検討をつけてから英語にしてます🍬
(英語も理解できるように頑張ろう…💪)
DBの種類と違い
firebaseのDatabaseは2種類あります。
Realtime Database
Cloud Firestore (Realtime Databaseの拡張版🌟)
動作や料金が変わってきます💰
基本は無料で使えます!👌
https://firebase.google.com/docs/database/rtdb-vs-firestore
基本はCloud Firestoreがオススメです💕
具体的な違いはここが参考になります!
https://techblog.kayac.com/rtdb-vs-firestore
Step1: firebaseのDBを作成
まずはここから!
Firebase
1. 「使ってみる」を押す
ログインしていない場合はログイン
そもそもアカウントがない場合は
Googleアカウントを作成してください🌟
![](https://i1.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_e7d5d1c0f5f5890672cfaece8041dec5-1024x594.png?resize=920%2C534)
2. 「プロジェクトを追加」を押す
![](https://i0.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_6b9d79332f45ffee7c3af9a2d9174c4b-1024x408.png?resize=920%2C367)
3. プロジェクト名を入力
下に表示されているsample-6a560が
プロジェクトIDになります。
![](https://i0.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_b9cd88ad12135ea11f0707b90d9152da-1024x680.png?resize=920%2C611)
4. Google アナリティクスの有無を選択
なしの場合は続行でプロジェクト完成
ありの場合は続行で次のアカウント選択
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_41a32c29ed7b727bbe08ba9168849ae3-1024x746.png?resize=920%2C670)
5. アカウントを選択
Default Account for Firebaseを選択
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_a89a629fb9b6fa8b7a0c005f04efeccf-1024x668.png?resize=920%2C600)
これでプロジェクトが完成🎉✨
プロジェクト概要画面へ移行します🌱
6. サイドメニューのDatabaseを押す
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_7ee8d593b2d2e782c420a8230c595fe3-1024x367.png?resize=920%2C330)
7. DBの種類を選択、作成
オススメはCloud Firestoreですが、
今回はシンプルにしたいので
firebase Realtime DBです🌟
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_74ed7b141f1ef9876dbd71f911ee9d83-1024x498.png?resize=920%2C447)
8. セキュリティルールを選択
テストモードで読み取りと書き込みを
許可しておきましょう!
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_c5a186c87723556714845322eedb120d-1024x604.png?resize=920%2C543)
これでDatabaseができました🤗🎉
Step2: Appの作成
ウェブアプリにfirebaseを追加していきます!
1. ダッシュボードから</>ウェブを選択
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_620150c70323ed558911078eb7867777-1024x367.png?resize=920%2C330)
2. アプリのニックネームを入力
Firebase Hostingの設定は今回はなしで⭕️
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_2693b5decf43f13fd1b01eefa8165f7c-1024x729.png?resize=920%2C655)
3.「コンソールに進む」を押す
コードはいつでも確認できるので飛ばしてOK
これでダッシュボードから
アプリが確認できるようになりました🤗
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_41c01d1451b01ad6af7e239ceadcc02e-1024x356.png?resize=920%2C320)
Step3: firebaseのインストール
兎にも角にもまずはインストール!!!🤖
https://firebase.google.com/docs/web/setup
referenceのnode.jsタブを見ていきます👀
Nuxtには初めからpakage.jsonがあるので
$npm initは不要ですね!
terminal
$ npm install --save firebase
これでpakage.jsonのdependenciesに
firebaseのバージョンが追加されます!
) file
1 2 3 4 5 6 7 8 |
{ "dependencies": { "firebase": "^7.12.0", "nuxt": "^2.0.0", "vue": "^2.6.11", "vue-template-compiler": "^2.6.11" }, } |
Step4: firebaseと連携する
plugin/firebase.jsを作ります🌟
Step3で見たreferenceの続きです。
firebaseをimport
firebase.initializeApp()アプリでfirebaseの初期化
その中にFirebase SDK snippetを貼り付け
(Step2で作成したアプリのコード)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import firebase from "firebase/app" import 'firebase/database' if (!firebase.apps.length) { firebase.initializeApp({ apiKey: "貼り付け", authDomain: "貼り付け", databaseURL: "貼り付け", projectId: "貼り付け", storageBucket: "貼り付け", messagingSenderId: "貼り付け", appId: "貼り付け", measurementId: "貼り付け" }) } export default firebase |
apiKeyなどの見方は
firebaseプロジェクトダッシュボードの
ここの歯車を押して…
![](https://i1.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_27cfd9214639c9b7174f0dab0ba08090-1024x365.png?resize=920%2C328)
この画面の下にある…
![](https://i1.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_196ca73fca6d63fd6f6c55c5dbdda8b6-1024x383.png?resize=920%2C344)
ここです!
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_12952cd965ae5fafb362a4f18218c021-1024x996.png?resize=920%2C895)
これで準備は整いました🙌
Step5: DBにinputでデータを追加してみる
現在のDBには何もありません。
![](https://i0.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_84f2fa9b10654a35fc4f42e6defbb4e6-1024x182.png?resize=920%2C164)
inputでこのデータを送信してみましょう📤
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_7518be32077333da6ec3679c2a3dbae8-1024x226.png?resize=920%2C203)
コード
) pages
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<template> <div class="page"> <label> <span> お名前: </span> <input type="text" v-model="user.name" > </label> <label> <span> email: </span> <input type="text" v-model="user.email" > </label> <button type="button" @click="submit" > Submit </button> </div> </template> <script> import firebase from '@/plugins/firebase' export default { data () { return { user: { name: "", email: "" }, } }, methods: { submit () { let Ref = firebase.database().ref() Ref.push({ name: this.user.name, body: this.user.email }) .then(response => { console.log(response, this.user) }) }, }, } </script> |
表示
Databaseに反映されていますね🤗
consoleに表示されたkeyとも
バッチリ合っています🌟
![](https://i0.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_e76c13acaabf143ea756c4e4cdb7f6c8-1024x466.png?resize=920%2C419)
解説
plugin/firebase.jsをimportする
- plugin/firebase.jsをimportする
- firebase.database().ref()
firebase.database()でデータが取り出せます。
ref()でdatabaseのURL指定をします。
引数が空=firebase.jsで貼り付けたURLです🌟https://firebase.google.com/docs/reference/js/firebase.databasehttps://firebase.google.com/docs/reference/js/firebase.database.Database#ref - push
変数にしたURLにデータをpushします📤
データの書き込みmethodには
set, push, update, transactionがあります。
setはまるごと上書きpushはkeyでまとまったデータを追加
https://firebase.google.com/docs/reference/js/firebase.database.Reference#set - .then
通信が成功した時の処理を書きます。
上手くいかない
テストモードではなく
ロックモードになっている可能性があります。
その場合はDatabaseのルールを
trueにしてみてください〜!
![](https://i1.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_0232c47ff20f2a605ce4f6de2d235382-1024x658.png?resize=920%2C591)
Step6: DBからデータを取得してみる
先ほどのデータを取得してみましょう!📥
keyでまとまったデータ全てではなく、
このkeyのnameだけを取得してみます🌟
![](https://i0.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_af93d902ba628e0e3c750528b648e761-1024x466.png?resize=920%2C419)
Databaseのkey(赤枠の部分)を押してみましょう!
下の階層になったことでURLが変わりましたね!
ちなみにURLはブラウザではなくここです👀
![](https://i2.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_5885f23530f39e2591bd4a70936ef9ac-1024x357.png?resize=920%2C321)
コード
) pages
methodsのfetchDataを追加し、
template内でdivで表示させます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<template> <div class="page"> <label> <span> お名前: </span> <input type="text" v-model="user.name" > </label> <label> <span> email: </span> <input type="text" v-model="user.email" > </label> <button type="button" @click="submit" > Submit </button> <button type="button" @click="fetchData" > fetchData </button> <div id="user.name" /> </div> </template> <script> import firebase from '@/plugins/firebase' export default { data () { return { user: { name: "", email: "" }, } }, methods: { submit () { let Ref = firebase.database().ref() Ref.push({ name: this.user.name, body: this.user.email }) .then(response => { console.log(response, this.user) }) }, fetchData () { let Ref = firebase.database().ref('/-M3Ub7gJeswkN3I7BSYk') Ref.on('value', function(snapshot){ document.getElementById("user.name").innerHTML = snapshot.child("name").val() }) }, }, } </script> |
表示
![](https://i1.wp.com/nuxt.alizlab.com/wp-content/uploads/2020/06/picture_pc_a8ba4503bde4c30692872d1297f55887.gif?resize=795%2C170)
解説
- firebase.database().ref()
下階層のURLに変更します!
firebase.database().ref('/{ key名 }') - Ref.on('value', function(snapshot){ 処理 })
データの取得をします🌟
https://firebase.google.com/docs/database/admin/retrieve-data - document.getElementById〜
div id="user.name"部分に表示させます - snapshot.child("name").val()
snapshot内(database内)で指定したURLの子
つまり今回でいうと-M3Ub7gJeswkN3I7BSYkの下の
nameの値だけを取得しています🌟