Vue.js で ToDo アプリを作る (Firebase Realtime Database 編)

前回の続き

Vue.js で ToDo アプリを作る - kntmr-blog

前回作成した ToDo アプリはデータを LocalStorage に保存していましたが、今回は Firebase Realtime Database に保存するようにしました。また、Vuex の Plugins は使わず、mutations のところで state を書き換えるついでに Firebase の API を呼び出しています。が、これでいいのかどうかは微妙なところ...。

あと、他の端末が Realtime Database のデータを変更したことを検知できるようにコールバックを実装しています。(VueFire 使えばもっと簡単にできると思いますが、今回はあえて使わないことに...)

ソースコードはこちら。

github.com

参考にしたドキュメントは以下。


以下、備忘録。

> npm install firebase --save

Firebase の初期化は src/main.js で実施。

import firebase from 'firebase/app'
import 'firebase/database'

var config = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "APPNAME.firebaseapp.com",
  databaseURL: "https://APPNAME.firebaseio.com",
  projectId: "APPNAME",
  storageBucket: "APPNAME.appspot.com",
  messagingSenderId: "xxxxxxxxxxxx"
}
firebase.initializeApp(config)

import firebase from 'firebase' だけだとコンソールに警告が出るようです。必要なものだけ import しましょうということっぽい。今回は Realtime Database だけ使うので以下のようにする。

import firebase from 'firebase/app'
import 'firebase/database'

ビルド & デプロイ

ビルドする。

> npm run build

Firebase プロジェクトとして初期化する。

> firebase login # ログイン
> firebase init
? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choi
ces. Hosting: Configure and deploy Firebase Hosting sites
? Select a default Firebase project for this directory: APPNAME # 既存のプロジェクトを選択
? What do you want to use as your public directory? dist # npm run build で dist に出力されるため、dist を指定する
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? File dist/index.html already exists. Overwrite? No # index.html は上書きしない

Firebase にデプロイする。

> firebase deploy

Android 端末でアクセスすると「ホーム画面に追加」が表示されます。初回アクセスでは表示されません。Android / iOS (Safari) ではオフラインでも動作します。また、Realtime Database の機能で端末間でデータが同期されます。オフラインで操作すると、次回オンラインになったときにデータが同期されます。すごい!

まとめ

もともと PWA について調べるつもりで始めましたが、最初に vue init pwa todo-app した以外は普通に Web アプリを作る感じになってしまいました。まだ、PWA や Service Worker あたりの理解が浅いので引き続き要学習。しかし、Realtime Database なかなか便利ですね。