LoginSignup
5
5

More than 1 year has passed since last update.

Vue3+Firebase(v9)の初期設定

Posted at

やりたいこと

VueからFirebase(Cloud Firestore)に接続しデータを取り出す、という単純な仕組みを実装しようとしました。

しかし、技術ブログのサンプルコードや公式ドキュメントのコードを使ったところ、行き詰まりました。

解決のポイント

先に解決のポイントを書いておくと、主に次の通りです。

  • Firebase v9 に従ったコードにする
  • await をasync内に書く
  • Firebaseコンソールにて、ルールを変更

公式ドキュメントのコード

Firestore公式ドキュメントのコードはこちらです。

最近Firebaseをインストールした方は、SDKのバージョンが9(v9)以上のはずです。v8以前とは書き方が若干違うようです。

技術ブログで紹介されているコードの多くは、v8に準拠したものに思われます。

基本的には公式ドキュメントのコードを参考にしましょう。

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
    // ...
};

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

// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
import { collection, getDocs } from "firebase/firestore";

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

変更した箇所

公式の通りに書いてもエラーが出ます。なので、何箇所か修正します。

main.js
import { createApp } from 'vue'
import App from './App.vue'
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
// 省略
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export default db; //追加
createApp(App).mount('#app')

設定ファイルの書き方です。

export default db を追加しています。

DBから読み込むコンポーネントを、仮にShowSample.vue とします(下のコードでは .js に変えています)。

そこには次の様なコードを書きます。

ShowSample.js
import db from "../main.js" //追加
import { collection, getDocs } from 'firebase/firestore'

設定ファイルでexport した dbをimportします。

methods に、次の functionを作ります。

ShowSample.js
getData: async function() { // async 追加
          const querySnapshot = await getDocs(collection(db, "users"));
          querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
          });

      }

公式ドキュメントでは awaitだけですが、それではこんなエラーが出ます。

Unexpected reserved word 'await'

対応策として、async を使い、その内部にawait を入れる形にします。

ここまで変えても、つぎのエラーがでます。

FirebaseError: Missing or insufficient permissions

ここで、Firebaseコンソール→Firestore Database の「ルール」へ行き、アクセス設定をテストモードに変更します。

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

本番環境へ移る時には、設定変更が必要です。

ひとまず、テスト環境ではFirestoreから読み込むことができました。

参考

Vue.jsでのasync,awaitの書き方

FirebaseとVue.jsでデータ登録取得機能を構築してみた

5
5
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
5
5