ジャコ Lab

プログラミング関連のメモ帳的ブログです

Vue プロジェクトから Firebase Realtime Database を使用する方法

zako-lab929.hatenablog.com

Firebase コンソール から Realtime Database の初期セットアップが作成が終わったら、Firebase SDK 経由で Vue プロジェクトから使えるようになっています。

この記事では、チャットのように文字列を送信及び受信するサンプルをまとめておきます。

前提1

この記事では Vue3 を使用します。
ローカルサーバー の起動まで出来ていることを前提とします。

プロジェクト作成はこの辺の記事が役立つかも

前提2

この記事では Firebase Realtime Database を使用します。
Firebase プロジェクト が作られていて Realtime Database が有効になっていることを前提とします。

Firebase の作成はこの辺の記事が役立つかも
Realtime Database の作成はこの辺の記事が役立つかも

では、早速 Realtime Database を使ってみます

Firebase SDK をインストール

$ yarn add firebase

SDK をセットアップ

src/firebase.tsっていうファイルを作成します!
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxx",
  projectId: "xxxxx",
  storageBucket: "xxxxx",
  messagingSenderId: "xxxxx",
  appId: "xxxxx",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

export { database };

Firebase のプロジェクト設定にある API-Key とかを設定します。

チャットのように文字を送信する

新規にファイルを作っても良いですが、面倒なので HelloWorld.vue を借りちゃお
<script setup lang="ts">
import { ref } from "vue";
import { ref as dbRef, push } from "firebase/database";
import { database } from "../firebase";

const text = ref("");

const onSend = () => {
  const helloWorldRef = dbRef(database, "/hello-world");
  push(helloWorldRef, text.value);
  text.value = ""
};
</script>

<template>
  <div class="hello-world-component">
    <input type="text" v-model="text" />
    <button type="button" @click="onSend">送信</button>
  </div>
</template>

<style scoped></style>

動作デモ

送信デモ
送信デモ

送信されたデータを受信して画面に表示する

onChildAdded を使います!
  <script setup lang="ts">
- import { ref } from "vue";
+ import { onMounted, reactive, ref } from "vue";
- import { ref as dbRef, push } from "firebase/database";
+ import { ref as dbRef, onChildAdded, push } from "firebase/database";
  import { database } from "../firebase";

  const text = ref("");
+ const receivedTexts = reactive<string[]>([]);

+ onMounted(() => {
+   const helloWorldRef = dbRef(database, "/hello-world");
+   onChildAdded(helloWorldRef, (snapshot) => {
+     const data = snapshot.val() as string;
+     receivedTexts.push(data);
+   });
+ });

  const onSend = () => {
    const helloWorldRef = dbRef(database, "/hello-world");
    push(helloWorldRef, text.value);
    text.value = "";
  };
  </script>

  <template>
    <div class="hello-world-component">
      <input type="text" v-model="text" />
      <button type="button" @click="onSend">送信</button>
+     <div class="box">
+       <p v-for="txt in receivedTexts">{{ txt }}</p>
+     </div>
    </div>
  </template>

  <style scoped>
+ .box {
+   border: 1px solid #000;
+ }
  </style>

動作デモ

受信デモ
受信デモ

まとめ

CSS は書いてないので雑な見た目ですが、Realtime Database と連携完了!