1
1

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 3 years have passed since last update.

Vuejs+TypeScript×Firestoreで、追加,削除,更新を行う方法メモ

Posted at

概要

Vuejs+TypeScriptを使って、Firestoreを扱うときのメモ

ドキュメント構成

Firestoreで下記のdocを更新したいときの方法

フィールド論理名 フィールド物理名
予算名 name string
予算額 cache number
色情報 color string

画面

新規作成と編集&削除を行う画面は下の感じで作成しました。

新規作成画面

image.png

編集&削除

image.png

画面ソース

Vue.jsでのdataの宣言

/view/plan/edit.vue
export default class PalnEdit extends Vue{

  private plan: Plan = { id : "" , name : "" , cache : 0 , color : "#" + Math.floor(Math.random() * 16777215).toString(16) }

}

データベースに合わせたTypeScriptでの方を定義

Plan.d.ts
export interface Plan {
  id?: string;
  name?: string;
  cache?: number;
  color?: string;
}

画面での値はv-modeより受け取る

<b-form-group class="form-group">
  <b-form-input
   type="number"
   placeholder="必須項目"
   v-model="plan.cache"
   :state="validated ? valid : null"
  />
   <b-form-invalid-feedback>{{ errors[0] }}</b-form-invalid-feedback>
</b-form-group>

登録や更新削除ボタンに@click:add()等のイベントも追加しておく

各処理のソース

追加

登録ボタンのイベントを定義

/view/plan/edit.vue
private add(){
    delete this.plan.id;
    firebase
      .firestore()
      .collection("plan")
      .add(this.plan)
      .then(function() {
      })
      .catch(function(error) {
      });
  }

更新

更新ボタンのイベントを定義
ドキュメントのidはurlパスから取得するように設定した。

/view/plan/edit.vue
private upd(){
      const docid = this.$route.params.id;
      const paln: Plan = this.plan;
      delete paln.id;
      firebase
        .firestore()
        .collection("plan")
        .doc(docid)
        .update(paln)
        .then(() => {

        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        }

削除

削除ボタンのイベントを定義
ドキュメントのidはurlパスから取得するように設定した。

/view/plan/edit.vue
  private del(){
    this.busy = true;
    const groupid = localStorage.groupid;
    const docid = this.$route.params.id;

    firebase
      .firestore()
      .collection("plan")
      .doc(docid)
      .delete()
      .then(function() {
      })
      .catch(function(error) {
        console.error("Error removing document: ", error);
      });
  }

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?