はじめに
前回firebaseの連携にかなり苦労してしまいました。
今回は教材を変えて、Firebaseの基本的なCRUDの部分の理解を深めていきます。
✅ゴール
・Firebaseの理解を深める
✅参考教材
Vue.js & FirebaseでTwitterライクなSNSアプリを作ってみよう!
Vue.jsでFirebaseを使ってみる
教材:Vue.js & FirebaseでTwitterライクなSNSアプリを作ってみよう!
この教材ではFirebaseでDatabase(collection)、Authentication、Hostingの実装。
※本番環境の作成として、デプロイする際は本来.envに環境変数を移すのがいいのかもしれない。(pitmarkは.env.productionに移してる。)
✅活用ライブラリ
FontAwesome、Stylus
✅内容
①プロジェクト作成(2-1)
$ vue create whisperer Vue CLI v3.8.2 ┌───────────────────────────┐ │ Update available: 4.3.1 │ └───────────────────────────┘ ? Please pick a preset: Manually select features ? Check the features needed for your project: Router, CSS Pre-processors ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Stylus ? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? No
②Firebaseとの連携(2-4)
・Vuefireのインストール
npm install firebase vuefire@next --save
関数firestore()
でvuefireは使える。
・main.jsへ追記(関連部分の抜粋)
import { firestorePlugin } from 'vuefire' import firebase from 'firebase' import 'firebase/firestore' Vue.use(firestorePlugin) firebase.initializeApp({ //ここでfirebaseのプロジェクトの紐づけ apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "" }) export const db = firebase.firestore() //dbという名前でアプリ内でFirestoreデータベースを使えるようにしている。 export const auth = firebase.auth() //authという名前でユーザー管理のためのサービスを使えるようにしている。
③リストの取得(2-5)
・Home.vueの編集(関連部分の抜粋)
~~テンプレート部分 <li v-for="whisper in whispers" :key="whisper.id" class="item"> {{whisper.content}} // firebaseのドキュメントキーに紐づいている {{whisper.uid}} // firebaseのドキュメントキーに紐づいている </li> ~~ <script> import { db } from '../main' // main.jsから先ほど定義した定数db(※Firestoreのデータベース)をインポート⇒firebase.firestore() export default { name: 'home', components: { }, data () { return { whispers: [] // からの配列をFirestoreから取得するwhisperデータの入れ物として用意 } }, firestore () { //Vuefireで定義されている関数。Vuefireのドキュメント読んでもいまいちわからず。。。 return { whispers: db.collection('whispers') // からの配列whispersにFirestore内にあるwhispersコレクション内のドキュメントを格納。 } } //ここまで追加 } </script>
※Firestoreのデータをページに表示させるには、データをインポートし、かつデータを格納する変数をあらかじめ用意する必要がある。
db.collection('コレクション名')
また関数firestore()
内でコレクション全体を取得したい場合は、db.collection(‘コレクション名’)と記載する。
👇FirebaseのDatabaseにデータを入れる。※usersコレクションは空。一度適当に作ってドキュメントを削除して作成。

※ドキュメントIDがIDになる。自動IDで作ってるけどかなり長くなるのが気になる点。また、Firestoreから取得したデータに関しては、idフィールドをキーとして用いることができる。
④投稿とユーザーの紐づけ。かつFirebaseから取得したデータのコンポーネント間の受け渡し。 2-6
※コードは割愛。
⑤Googleログイン 3-1 公式
Firebaseが提供している関数を用いてHeader.vueに実装。
import { auth } from '../main' // 追記(※main.js記載のfirebase.auth()を読み込み。)
サインイン
const provider = new firebase.auth.GoogleAuthProvider() auth.signInWithPopup(provider)
サインアウト
auth.signOut()
⑥認証状態の取得 3-2 公式
Firebaseが提供している関数を用いる。
auth.onAuthStateChanged(user => { this.currentUser = user })
⑦データの追加 3-3 公式
※4-1の新規投稿も同じ。
追加の関数にはsetとaddがある。
.set:IDを指定できる(ユーザーIDなど)。
db.collection('<コレクション名>').doc('<ドキュメントのID>').set({ '<フィールド1>': '<フィールド1の値>', '<フィールド2>': '<フィールド2の値>', '<フィールド3>': '<フィールド3の値>' })
.add
db.collection('<コレクション名>').add({ '<フィールド1>': '<フィールド1の値>', '<フィールド2>': '<フィールド2の値>', '<フィールド3>': '<フィールド3の値>' })
⑧ユーザーページ 3-4
Vue Routerでルーティングを自動生成。
以下で、現在のルートオブジェクトを指す$routeプロパティからuidパラメータを取得できる。(これを取得したユーザーIDと紐づける)
this.$route.params.uid
⑨ユーザーが投稿したもののみユーザーページに表示する 3-5 公式(クエリ)
db.collection('<コレクション名>').where('<フィールド名>','==','<値>')
⑩投稿の削除 4-2 公式
db.collection('<コレクション名>').doc('ドキュメントID').delete()
⑪投稿の更新 4-3 公式
👉{merfe: true}を最後に設定することで、指定されていないフィールドの値を維持しつつ、更新したいフィールドの値のみ更新される。
db.collection('<コレクション名>').doc(<ドキュメントID>).set({
'<フィールド1>': <フィールド1>,
'<フィールド2>': <フィールド2>,
'<フィールド3>': <フィールド3>
}, { merge: true })
⑫デプロイ
npm run build // distを作成 npm install -g firebase-tools // Firebase CLIをインストール firebase login // Googleアカウントでログイン firebase init // Firebaseプロジェクトの初期化(プロジェクトの紐づけなど行う) ? Are you ready to proceed? Yes ? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. Hosting: Configure and deploy Firebase Hosting sites ? Please select an option: Use an existing project ? Select a default Firebase project for this directory: // firebaseで作ったプロジェクト ? What do you want to use as your public directory? dist // デプロイするディレクトリ名を設定 ? Configure as a single-page app (rewrite all urls to /index.html)? Yes // 存在しないページへアクセスしたときTopにリダイレクトするか ? File dist/index.html already exists. Overwrite? No firebase deploy
完成
✅メインページ

✅開発画面(コンソール)

完成品 ※誤ってエリアを日本ではなく海外にしてしまったため遅いかも。。。
躓いた点
✅import {} の意味が分からない
解決:分割代入というらしい。
import { firestorePlugin } from 'vuefire'
JavaScriptの代入において時々現れる、括弧で囲まれた変数名は何なのか
おわりに
予想以上にFirebaseの学習コストが高く驚き。もう少し教材を探して学習を進めていきたい。
ただ、LaravelでGoogleログインを実装(この教材)するよりかは手軽なのはよくわかった。
チュートリアル系サイト
※要書籍での学習
Vue.jsとFirebaseで、noteライクなSNSアプリを5時間で作ろう! 同著者の教材っぽい。500円かかるけどシンプルでわかりやすそう。
Vue.js + FirebaseでTodoアプリを作る CRUDをVuefire用いず実装している。(いろいろ方法あるっぽい)
【Nuxt.js】firebase導入編(Firestore版):データの追加 取得をしよう 追加は.add()、取得は.get()だけどpushとかしててちょっとややこい。
参考
Cloud Firestore with Vue.jsで簡単なメモアプリを実装する CRUDの参考に。
FirebaseからVue.jsへデータを取り出すサンプルをいくつか投稿してみる CRUDの参考に。
Firebase Realtime DatabaseとFirestoreを使い分けていこうなという話
【v2対応】Nuxt.jsとFirebaseを組み合わせて爆速でWebアプリケーションを構築する 認証はGoogleでやるのがおすすめらしい。
光の速さでデプロイ ~ Vue + Firebase hosting ことはじめ ~ デプロイも試しに早くしてみたい。
Vueやるならvue-routerは知っておこう router.pushなどの説明有
コメントを残す