わいの日記

ありがちエンジニアブログ

Vuefireの使い方 その1

vuefireの使い方を簡単なcrud構築することで紹介します

今回は新規登録f:id:exhikkii:20180810000150p:plain

vuefireはVue.jsでfirebaseをいい感じに使えるプラグインですね

では早速。。
今回はデザインがん無視します(Vuetifyいいよ〜)

プロジェクト作成

vue init webpack vuefire-tutorial
cd vuefire-tutorial
yarn dev

buildはstandalone、
vue-routerはy
あとはなんでもいいです
f:id:exhikkii:20180809230342p:plain

新規作成画面

AddPostコンポーネント作成
touch src/components/AddPost.vue // AddPost.vue作成
routingの設定

ふつうにvue-routerの書き方するだけですね
HelloWorld.vueに関する記述は消して大丈夫です

import Vue from 'vue'
import Router from 'vue-router'
import AddPost from '@/components/AddPost'

Vue.use(Router)

export default new Router({
  mode: 'history', // historyモードに変更
  routes: [
    {
      path: '/add', //localhost:8080/addでアクセスできます
      name: 'AddPost',
      component: AddPost
    }
  ]
})

以下をコピペしてください
src/components/AddPost.vue

<template>
  <div>
    <form @submit.prevent="addPost">
      <div>
        <input type="text" v-model="post.title">
      </div>
      <div>
        <textarea v-model="post.content"></textarea>
      </div>
      <div>
        <input type="submit" value="submit">
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'AddPost',
  data () {
    return {
      post: {
        title: '',
        content: ''
      }
    }
  },
  methods: {
    addPost () {
      console.log('title', this.post.title)
      console.log('content', this.post.content)
    }
  }
}
</script>

inputにv-modelをあてがって、
formにsubmitイベントバインドさせています
とりあえずsubmitすればコンソール上に入力した値が表示されるはずです

firebaseプロジェクト作成

firebaseのコンソールで適当なプロジェクトを1つ作成してください

「ウェブアプリにFirebaseを追加」というところをクリックするとapikeyとか出てきます
それらをVueプロジェクトに登録します
f:id:exhikkii:20180809232730p:plain

firebase.js作成
mkdir src/config
touch src/config/firebase.js
firebase vuefireのインストール
yarn add firebase vuefire
apikeyなどの登録

※ xxxxのところは各自の値を代入してください
src/config/firebase.js

import Firebase from 'firebase'

const config = {
  apiKey: 'xxxxxxx',
  authDomain: 'xxxxxxx',
  databaseURL: 'xxxxxxx,
  projectId: 'xxxxxxx',
  storageBucket: 'xxxxxxx',
  messagingSenderId: 'xxxxxxx'
};

const app = firebase.initializeApp(config);
export default app.database()
vuefireの設定

src/main.jsに下の2行を追加してください

import VueFire from 'vuefire'
Vue.use(VueFire)
AddPostの修正

src/components/AddPost.vueを以下のように修正してください

<script>
import db from '@/config/firebase' // firebase(db)をimportする
export default {
  name: 'AddPost',
  data () {
    return {
      post: {
        title: '',
        content: ''
      }
    }
  },
  firebase: {
    posts: db.ref('posts') // postsでfirebaseのdbのpostsを参照できる
  },
  methods: {
    async addPost () {
      try {
        await this.$firebaseRefs.posts.push({ // pushでデータを作成できる
          title: this.post.title,
          content: this.post.content
        })
        // 入力欄を空にする
        this.post.title = ''
        this.post.content = ''
        // トップページに繊維させる
        this.$router.push('/index')
      } catch (err) {
        console.log('err', err)
      }
    }
  }
}
</script>

firebaseのREALTIME DATABASEの作成

テストモードで作成してください
もしくはルールを下記のように設定してください
そうでないとデータの読み書きができません
f:id:exhikkii:20180809235828p:plain


できた
f:id:exhikkii:20180810000150p:plain

長くなってきたのでとりあえず今回はここまで
編集、読み込み、削除は次回以降