LoginSignup
3
3

More than 3 years have passed since last update.

【Vue.js】 axios / firebaseを利用して、データのやり取り

Last updated at Posted at 2020-10-14

【ゴール】

axios / firebaseを利用して、データのやり取り

画面収録 2020-10-14 11.05.15.mov.gif

【環境】

mac catarina 10.156
Vue.js v2.6.12

【実装】

firebaseのセットアップ

下記URLにアクセス、googleアカウントの登録、作成
https://firebase.google.com/

1 プロジェクト作成

スクリーンショット 2020-10-14 11.09.51.png

2 アナリティクスはOFFで構いません。

スクリーンショット 2020-10-14 11.11.08.png

3 cloud firestroeにてdatabaseの作成

スクリーンショット 2020-10-14 11.12.46.png

4 テストモードで構いません

スクリーンショット 2020-10-14 11.13.27.png

5 ロケーションはデフォルトのままで構いません

スクリーンショット 2020-10-14 11.14.22.png

6 作成完了

スクリーンショット 2020-10-14 11.15.01.png

7 左のメニューバーの設定→プロジェクトの設定→プロジェクトIDを確認

スクリーンショット 2020-10-14 11.15.30.png

axiosのインストール

※ワークスペース作成は割愛

Mac.terminal
$ npm install axios

コード

<template>内
※「@click="textSend"」でaxiosが発火(下記に詳細ページ貼ってます)
※「v-for」で繰り返し処理で表示

App.vue

<template>
  <div>
    <h2>Post,new</h2>
    <div>
      <div class="form">
        <textarea name="text" cols="100" rows="10" v-model="text"></textarea
        ><br />
        <button @click="textSend">send</button>
      </div>
    </div>
    <div v-for="post in posts" :key="post.text">
      {{ post.fields.text.stringValue }}
    </div>
  </div>
</template>

<script>内
※「import axios from "axios";」でaxioをインポート
※「created」でページ読み込みじにデータベースから情報を取得
※「posts」に取得したデータを配列として渡す
※「stringValue」はデータ型、指定してあげる
※「this.text = '';」でtextarea内を空にする

app.js

import axios from "axios";

export default {
  data() {
    return {
      text: "",
      posts: [],
    };
  },
  created() {
    axios
      .get(
        "https://firestore.googleapis.com/v1/projects/texposts/databases/(default)/documents/text"
      )
      .then((res) => {
        this.posts = res.data.documents;
        console.log(res);
      });
  },
  methods: {
    textSend() {
      axios
        .post(
          "https://firestore.googleapis.com/v1/projects/7番のプロジェクトID/databases/(default)/documents/text",
          {
            fields: {
              text: {
                stringValue: this.text,
              },
            },
          }
        )
        .then((res) => {
          console.log(res);
        });
      this.text = "";
    },
  },
};
</script>

【まとめ】

■firebaseをセットアップ
■axiosをインストールしてhttp通信を可能に
■記述。URL等のタイポに気を付ける

【オススメ記事】

■ 【Vue.js】 IF文・For文 条件分岐、繰り返し処理
https://qiita.com/tanaka-yu3/items/0ccf9a11525331b764de

■【Vue.js】クリック処理 @click
https://qiita.com/tanaka-yu3/items/e578cadf35a7bc024770

■ 【Vue.js】Vue.jsでfontawsome(Free版)を使用する方法 
https://qiita.com/tanaka-yu3/items/86d05241f72674d186f6 

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