![見出し画像](https://assets.st-note.com/production/uploads/images/76772991/rectangle_large_type_2_9c8133d6e9d535d488b0f11e0cfa4d1b.png?width=800)
Vue.js勉強記録その37 外部サービスを利用しよう 6-4 ver1
こちらの書籍で勉強中です。
今回は、Firebase SDKを使います。
ですが、Firebaseのバージョンが、こちらの書籍の時と変わっていて、書籍通りに記述しても動きませんでした。
ので、書籍の内容とは少し違う感じになります。
■プロジェクトにWebアプリケーションを追加する
Firebaseの管理画面の、左上にある、「プロジェクトの概要」の右にある、歯車マークから、プロジェクトの設定をクリック。
![](https://assets.st-note.com/img/1650360034927-dW9vCJutZi.png)
アプリを追加から、「</>」のアイコンをクリック。
![](https://assets.st-note.com/img/1650360155130-pLQ1khtBfz.png)
アプリの名前を入力して、アプリを登録をクリックする。
■RealtimeDatabaseにアクセス
ここから書籍では、CDNを使う方法でコードを書いているが、Firebaseのバージョンが違い、どうしても出来なかった。以下のサイトを参考に、CDNではなく、npmでfirebaseをインストールする形でDBの表示を目指した。
まずは、firebaseのサイトで、コピペするコードをコピーする。
![](https://assets.st-note.com/img/1650360629874-Xfi7lqoWnU.png?width=800)
コマンドで、以下を実行
npm install firebase
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// 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: "xxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
createApp(App).mount('#app')
<template>
<section class="alert alert-primary">
<h1>{{ data.title }}</h1>
<p>{{ data.message }}</p>
<table class="table table-light table-striped">
<thead>
<tr>
<th>Name</th>
<th>Mail</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="(data, key) in data.fire_data" v-bind:key="key">
<td>{{ data.name }}</td>
<td>{{ data.age }}</td>
<td>{{ key }}</td>
</tr>
</tbody>
</table>
</section>
</template>
<script>
import { onMounted, reactive } from "vue";
import { getDatabase, ref, child, get } from "firebase/database";
export default {
setup(props) {
const data = reactive({
title: "Firebase",
message: "This is Firebase sample",
id: 0,
fire_data: null,
});
const getData = () => {
const db = getDatabase();
const dbRef = ref(db);
get(child(dbRef, "person"))
.then((snapshot) => {
if (snapshot.exists()) {
data.fire_data = snapshot.val();
} else {
console.log("no data");
}
})
.catch((err) => {
console.log("error");
});
};
onMounted(() => {
getData();
});
return { data, getData };
},
};
</script>
まず、importで、必要な機能を読み込む
import { getDatabase, ref, child, get } from "firebase/database";
メソッドgetDataの中身が、主にデータベースにアクセスする内容。
アクセスできたら、取得できたデータを、fire_dataに代入する。(そうすると描画される。)
![](https://assets.st-note.com/img/1650361322434-OpluggKT0A.png?width=800)
■まとめ
随分前回の記事から間が空いてしまった。
今回は、バージョン違いにより、書籍と大分違う書き方になってしまいました。
それでも、ちゃんと情報を入手できて、データを表示するところまで来たので、とりあえず良しとしよう。
この記事が気に入ったらサポートをしてみませんか?