LoginSignup
12
10

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-12-06



この記事は、「Firebase Advent Calendar 2020」の6日目の記事です。

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


事前準備


バックエンド

まずは、バックエンドを構築していきます。
以前の記事で、認証機能までを追加したので今回はCloud Firestoreを設定します。

画像
画像
画像
画像
画像

これだけでバックエンドの構築は完了になります :thumbsup:


フロントエンド

次に、フロントエンドを構築していきます。

実行環境

  • node v12.7.0
  • npm v6.13.4


src/views

Main.vue

<template>
    <div class='main'>
        <!--メニュー-->
        <Menu></Menu>
        <b-container>
            <b-row>
                <b-col sm='12' class='mb-3'>
                    <h3>ログイン済</h3>
                    <hr>
                </b-col>
                <b-col sm='3' class='mx-auto mb-3'>
                    <b-form-input v-model='id' placeholder='id'></b-form-input>
                    <b-form-input v-model='name' placeholder='name'></b-form-input>
                </b-col>
                <b-col sm='12' class='mb-5'>
                    <b-button variant='primary' v-on:click='postData'>登録</b-button>
                </b-col>
                <b-col sm='3' class='mx-auto mb-3'>
                    <b-table striped hover :items='items'></b-table>
                    <b-form-input v-model='text' placeholder='id'></b-form-input>
                </b-col>
                <b-col sm='12' class='mb-5'>
                    <b-button variant='success' v-on:click='getData'>表示</b-button>
                    <hr>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

<script>
    import Menu from '@/components/Menu.vue'
    // Firebase読み込み
    import firebase from 'firebase'

    export default {
        name: 'Main',
        components: {
            Menu
        },
        data() {
            return {
                id: '',
                name: '',
                text: '',
                items: []
            }
        },
        methods: {
            getData: function () {
                const  db = firebase.firestore();
                // データ取得
                db.collection('users').where('id', '==', Number(this.text)).get(
                ).then((querySnapshot) => {
                    querySnapshot.forEach((doc) => {
                        // テーブル表示
                        this.items = [doc.data()];
                    });
                }).catch((error) => {
                    console.log(error);
                    // テーブルリセット
                    this.items = [];
                });
            },
            postData: function () {
                const db = firebase.firestore();
                // データ登録
                db.collection('users').add({
                    id: Number(this.id),
                    name: String(this.name)
                }).then((response) => {
                    console.log(response);
                }).catch((error) => {
                    console.log(error);
                });
            }
        }
    }
</script>

<style scoped>
    h3 {
        margin-top: 50px;
        text-align: center;
    }
</style>


Firebaseを読み込みます。

// Firebase読み込み
import firebase from 'firebase'


データ取得用の関数を設定します。

getData: function () {
    const  db = firebase.firestore();
    // データ取得
    db.collection('users').where('id', '==', Number(this.text)).get(
    ).then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            // テーブル表示
            this.items = [doc.data()];
        });
    }).catch((error) => {
        console.log(error);
        // テーブルリセット
        this.items = [];
    });
},


データ登録用の関数を設定します。

postData: function () {
    const db = firebase.firestore();
    // データ登録
    db.collection('users').add({
        id: Number(this.id),
        name: String(this.name)
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    });
}


簡易ローカルサーバーで確認してみます。

npm run serve


ローカルサーバーを立ち上げて、ログインしてみます。データの登録と取得ができるようになっています :bulb:

画像

Firebaseのコンソールで登録できているか確認してみます。

画像


FirebaseとVue.jsでデータ登録取得機能の構築ができました :thumbsup:

Firebaseは、Cloud Firestoreを利用することで細かい設定はまだまだあったりはしますが、手軽にデータの登録取得機能も構築できるので、AWS Amplifyと同じくサーバーレスアプリケーションを構築する時にとても便利です :bulb:

AWS Amplifyでのデータ登録取得機能の記事、「AWS AmplifyとVue.jsでデータ登録取得機能を構築してみた」とも比べてみて頂ければと思います :grinning:


Vue.js・Firebaseについて、他にも記事を書いています。よろしければぜひ :bow:
tags - Vue.js
tags - Firebase

やってみたシリーズ :grinning:
tags - Try




book

12
10
1

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
12
10