LoginSignup
0
0

More than 3 years have passed since last update.

【Nuxt.js】Firebaseとの連携方法

Last updated at Posted at 2020-11-26

firebaseパッケージのインストール

ターミナル
プロジェクト名$ npm install --save firebase

firebase pluginの作成

ターミナル
プロジェクト名$ touch plugins/firebase.js
plugins/firebase.js
import firebase from 'firebase/app'
import 'firebase/firestore'

if (!firebase.apps.length) {
  firebase.initializeApp(
    {
      apiKey: process.env.FIREBASE_API_KEY,
      authDomain: process.env.FIREBASE_AUTH_DOMAIN,
      databaseURL: process.env.FIREBASE_DATABASE_URL,
      projectId: process.env.FIREBASE_PROJECT_ID,
      storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
      messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
      appId: process.env.FIREBASE_APP_ID,
      measurementId: process.env.FIREBASE_MEASUREMENT_ID
    }
  )
}

export default ({ app }, inject) => {
  inject('firebase', firebase);
}

環境変数の設定方法はこちら↓
【Nuxt.js】「dotenv」を使った環境変数の設定方法

nuxt.config.jsの設定

nuxt.config.js

//...省略

  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    '~/plugins/firebase'
  ],

//...省略

動作確認

pages/index.vue内に送信ボタンを設け、
クリックでfirestoreにデータを送る。

pages/index.vue
<template>
  <div class="container">
    <button @click="submit">送信</button>
  </div>
</template>

<script>
export default {
  methods: {
    submit() {
      const db = this.$firebase.firestore();
      db.collection('user').add({ name: 'hoge' })
        .then(() => {
          console.log('成功');
        })
        .catch((e) => {
          console.log(e.message);
        });
    }
  }
}
</script>

スクリーンショット 2020-11-26 23.10.54.png

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