LoginSignup
3
2

More than 3 years have passed since last update.

Nuxt.jsでFirebase Realtime Databaseの読み書きを行う

Last updated at Posted at 2021-04-15

Nuxt.jsのWebアプリから、FirebaseのRealtimeDatabaseの読み書きを行ったので、手順をまとめておきます。

Firebase Realtime Databaseの作成

事前にFirebaseコンソールからプロジェクトを作成し、Webアプリを追加します。
create_app.jpg
その後、Realtime Databaseを作成してください。
作成時の各設定は任意に行ってOKです。
create_db.jpg

Nuxt.js側にFirebaseの設定

Nuxt.js側でFirebaseを操作するため、必要なモジュールをインストールして設定していきます。
今回は、Nuxt.jsでのFirebaseの操作に便利な nuxtjs/firebaseもインストールします。

下記コマンドを実行してください。

npm install --save firebase @nuxtjs/firebase

次に、 nuxt.config.js に下記設定を追加します。

nuxt.config.js
export default {

  modules: [
    [
      '@nuxtjs/firebase',
      {
        config: {
          apiKey: '<apiKey>',
          authDomain: '<authDomain>',
          projectId: '<projectId>',
          storageBucket: '<storageBucket>',
          messagingSenderId: '<messagingSenderId>',
          appId: '<appId>',
          measurementId: '<measurementId>'
        },
        services: {
          database: true // Realtime Databaseの使用を宣言
        }
      }
    ]
  ],

}

<apiKey> など、それぞれの項目に指定する値は、Firebaseコンソールの「プロジェクトの設定」から、下記のように確認可能です。
(Nuxt.jsのプロジェクトに追記する際はenvファイルを利用するなどしてください)
firebase_setting.jpg

データの読み書き

基本的にデータの読み書きはドキュメント通りです。
今回は例として、下記のように実装します。

pages/index.vue
<template>
  <div>
    <button @click="increment">send</button>
    <span>count:</span>
    <span>{{ count }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  mounted() {

    // RealtimeDatabaseの更新を検知
    this.$fire.database.ref('count').on('value', (snapshot) => {
      this.count = snapshot.val();
    })
  },
  methods: {

    // RealtimeDatabaseを更新
    increment() {
      this.$fire.database.ref('count').set(
        ++this.count
      );
    }
  }
}
</script>

ページを確認すると、このように表示されます。
page.png
「send」ボタンを押すことで、 increment() が呼ばれ、Realtime Database上の値が更新されます。
rtdb.jpg
Realtime Database上の値が更新されると、Webアプリ側は更新を検知して自動で値が同期されます。
page2.png

これだけです!
さくっと導入でき、とても簡単ですね!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2