LoginSignup
4
2

More than 3 years have passed since last update.

【Vue.js】Firebase独自のメソッドをまとめてみよう

Posted at

firebaseモジュールのセットアップ

$ yarn add firebase --save
main.js
import firebase from "firebase";

const config = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: ""
};
firebase.initializeApp(config);

コンポーネントでの準備

router/index.js
import signup from "@/components/signup";

export default new Router({
  routes: [
    {
      path: "/signup",
      component: signup
    },
  ]
})
components/signup.vue
# コンポーネント毎にモジュール読み込み
import firebase from "firebase";

Usage ユーザー作成、認証系

サインアップ

signUp: function() {
  firebase
    .auth()
    .createUserWithEmailAndPassword(this.email, this.password)
    .then(user => {
      alert(user.email);
    })
    .catch(error => {
      alert(error.message);
    });
}

サインイン

signIn: function() {
  firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(user => {
      alert("success");
      this.$router.push("/profile");
    })
    .catch(error => {
      alert(error.message);
    });
}

ログイン中ユーザーのデータ取得

data () {
  return {
    email: firebase.auth().currentUser.email
  }
}

ユーザーがログイン中なら、ユーザー情報を返すメソッド(ログインチェック)

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    //ユーザーログイン時の処理
  } else {
    //ユーザーログアウト時の処理
  }
})

Usage クラウドデータベース

firestoreの全件データを取得

firebase.firestore().collection("message").get()
  .then(function(query) {
    query.forEach(function(doc) {
      console.log(doc.data());
    });
  }).catch(function(e) {
    alert(e);
  });

firestoreの全件データの中から、条件を絞って取得

firebase.firestore().collection("message").where("name", "==", "tom").get()
  .then(function(query) {
    query.forEach(function(doc) {
      console.log(doc.data());
    });
  }).catch(function(e) {
    alert(e);
  });

firestoreにデータを追加

firebase.firestore().collection("message").add({
  name: this.nameData
})
  .then(function() {
    alert("成功しました");
  }).catch(function(e) {
    alert("失敗しました");
  });

firestoreのデータを削除

firebase.firestore().collection("message").doc("directMessage").delete(
  .then(function() {
    alert("成功しました");
  }).catch(function(e) {
    alert("失敗しました");
  });
4
2
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
2