4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nuxt.jsとFirestoreでリアルタイム反映(vuexを使わずお手軽実装) 

Last updated at Posted at 2020-03-19

Firestoreの設定

  1. FIrestoreのプロジェクト作成
  2. コレクション作成(RDBでいうテーブル)
  3. ドキュメント作成(RDBでいうレコード)

Nuxt.js側の設定

firebaseをインストール

npm install firebase --save

firebaseのapi情報をfirebaseのコンソールで確認

  1. 左上の歯車から[プロジェクトを設定]を選択
  2. マイアプリから[アプリを追加]
  3. プラットフォーム[>]を選択
  4. API情報が表示される

firebaseのAPI情報の値を参考にpluginに記述

plugins/firebase.js


import firebase from 'firebase/app'
import 'firebase/firestore'

firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
})
const db = firebase.firestore()
export default db

nuxt.config.jsへ追記


plugins: [
  { src: '~/plugins/firebase' }
]

データ操作方法


<script>
import db from '~/plugins/firebase'

export default {
  data() {
    return {
      users: []
    }
  },
  methods: {
    /*
     * 一覧取得
     * onSnapshot()メソッド:リアルタイム反映する
     * get()メソッド:リアルタイム反映しない
     */
    getUsers() {
      db.collection(コレクション名).onSnapshot((docs) => {
        this.users = [] // リアルタイム反映のため一度リセット
        docs.forEach((doc) => {
          let user = doc.data()
          user.id = doc.id // 一意のドキュメントIDをプロパティに追加(後のupdateやdeleteでドキュメントIDが必要なため)
          this.users.push(user)              
        })
      })
    },
    /*
     * 検索
     * 複数クエリはwhereをつなげる
     */
    searchUsers() {
      db.collection(コレクション名)
        .where('name', '==', 'boby')
        .where('age', '>', 20)
        .get((docs) => {
          this.users = []
          docs.forEach((doc) => {
            let user = doc.data()
            user.id = doc.id
            this.users.push(user)              
          })
      })
    },
    /*
     * ドキュメント新規登録
     */
    addUser() {
      db.collection(コレクション名).add({
        name: 'Boby',
        age: 23
      })
    },
    /*
     * ドキュメント削除
     */
    deleteUser(docId) {
      db.collection(コレクション名).doc(docId).delete().then(() => {
        //success
      })
      .catch((error) => {
        //error
      })
    },
    /*
     * ドキュメント更新
     */
    updateUser(docId) {
      db.collection(コレクション名).doc(docId).update({
        name: 'Mike',
        age: 18
      }).then(() => {
        //success
      })
      .catch((error) => {
        //error
      })
    }
  }
}
</script>

参考:
https://firebase.google.com/docs/firestore/quickstart?hl=ja#initialize

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?