【ゴール】
Vue.jsでfirebaseを使用してログイン機能、ユーザー登録機能作成
【環境】
mac catarina 10.156
Vue.js v2.6.12
【実装】
firebaseをセットアップ
firebaseのURL
https://firebase.google.com/
※プロジェクトの作成は詳しくこちらで紹介しています。
https://qiita.com/tanaka-yu3/items/192886ce66522f027365
1 ログインし、プロジェクト作成後、Authenticationの「メール、パスワード」を有効に変更
2 プロジェクトのWEB_APIキーを確認
左のメニューバー→設定→プロジェクトを設定,ウェブAPIキーを確認
firebase auth apiを確認
「firebase auth api」の公式サイトから、使いたい機能のドキュメント確認
https://firebase.google.com/docs/reference/rest/auth
※※確認する項目は以下2点※※
■エンドポイントのURL
■応答ペイロード(firebaseに送る情報、データのことです。)
コーディング
※「axios」を事前にインストール(http通信を利用する為)
※「data」には先ほど1で確認し、必要である「email, password」のデータをセット
※「.then」の記述はコンソールでデータの確認をする為
※「this.email = "";」は入力完了後に空に戻す処理です。
※「input」に「v-model」ディレクティブを忘れないように!!正常にデータ渡せません
※「returnSecureToken」は常に「true」を返します
<template>
<div>
<h2>Login</h2>
<div class="form">
<label for="emial">Email:</label>
<input type="text" v-model="email" />
</div>
<div class="form">
<label for="password">password:</label>
<input type="password" v-model="password" />
</div>
<div class="form">
<button @click="Login">ログイン</button>
</div>
</div>
<template>
<script>
import axios from "axios";
export default {
data() {
return {
email: "",
password: "",
};
},
methods: {
Login() {
axios
.post(
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=あなたのWEB_APIキー",
{
email: this.email,
password: this.password,
returnSecureToken: true,
}
)
.then((res) => {
console.log(res);
});
this.email = "";
this.password = "";
},
},
};
</script>
<template>
<div>
<h2>Register</h2>
<div class="form">
<label for="emial">Email:</label>
<input type="text" v-model="email" />
</div>
<div class="form">
<label for="password">password:</label>
<input type="password" v-model="password" />
</div>
<div class="form">
<button @click="Register">登録</button>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
email: "",
password: "",
};
},
methods: {
Register() {
axios
.post(
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=あなたのWEB_APIキー",
{
email: this.email,
password: this.password,
returnSecureToken: true,
}
)
.then((res) => {
console.log(res);
});
},
},
};
</script>
【まとめ】
■firebaseのプロジェクトでAuthenticationのメールパスワードを有効に
■firebase auth apiで使用したい機能のドキュメントを確認
■URL、タイポのミスがないように記述
【オススメ記事】
■ 【Vue.js】 axios / firebaseを利用して、データのやり取り
https://qiita.com/tanaka-yu3/items/192886ce66522f027365
■ 【Vue.js】クリック処理 @click
https://qiita.com/tanaka-yu3/items/e578cadf35a7bc024770
■ 【Vue.js】 IF文・For文 条件分岐、繰り返し処理
https://qiita.com/tanaka-yu3/items/0ccf9a11525331b764de