概要
Vuejs+TypeScriptを使って、Firestoreを扱うときのメモ
ドキュメント構成
Firestoreで下記のdocを更新したいときの方法
フィールド論理名 | フィールド物理名 | 型 |
---|---|---|
予算名 | name | string |
予算額 | cache | number |
色情報 | color | string |
画面
新規作成と編集&削除を行う画面は下の感じで作成しました。
新規作成画面
編集&削除
画面ソース
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);
});
}