firestore可以利用setDoc()或updateDoc()來更新資料
使用setDoc()
import { doc, setDoc } from "firebase/firestore";
// Add a new document in collection "cities"
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
使用updateDoc(),跟setDoc()不同的是,不會去更動其他既有的欄位
import { doc, updateDoc } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Set the "capital" field of the city 'DC'
await updateDoc(washingtonRef, {
capital: true
});
操作陣列
import { doc, updateDoc, arrayUnion, arrayRemove } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Atomically add a new region to the "regions" array field.
await updateDoc(washingtonRef, {
regions: arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
await updateDoc(washingtonRef, {
regions: arrayRemove("east_coast")
});
對一個數字欄位可以進行增加或減少的更動
import { doc, updateDoc, increment } from "firebase/firestore";
const washingtonRef = doc(db, "cities", "DC");
// Atomically increment the population of the city by 50.
await updateDoc(washingtonRef, {
population: increment(50)
});
接下來,我們利用範例來介紹這些語法的實際應用
執行更新的第一個動作是讀取讀取原本的內容,再將新的內容寫回firestore。
首先,新增一個/src/components/account/Profile.vue
<script setup lang="ts">
</script>
<template>
<v-container>
<v-text-field label="姓名"></v-text-field>
<v-btn color="primary" >更新</v-btn>
<v-btn color="secondary" >回首頁</v-btn>
</v-container>
</template>
在/src/route.ts裡,新增對應的route。
{
path: '/profile',
name: 'profile',
component: () => import('./components/account/Profile.vue')
}
因為希望一打開就去讀取資料,所以,利用inject()取得登入資料,先利用v-model綁定login.name。