# Firestore 更新資料edit & update 教學影片:[點這邊](https://www.youtube.com/watch?v=W1DwGBeS-KU&list=PLB4AdipoHpxYPjGo0n2m6tmCLud_iSEbv&index=36) > * ### 注意:這篇文章上半部只是從database中更新資料 > * ### 下半部才有realtime喔!( 使用watcher()) --- ## edit 修改資料 > 進入Products.vue [color=black] > :baby_chick: 在 v-for 循環的刪除按鈕中增加 **@click="editProduct(singleP)"** ```html= <span @click="editProduct(singleP)"> <i class="fas fa-pen"></i> </span> ``` :baby_chick: 設定一個新的資料 **activeItemId: null** 用來在編輯時傳入 **正在編輯的資料id** ```javascript= data(){ return { editState: false, activeItemId: null, value: null, allproducts:[], product:{ name:null, price:null } } } ``` :baby_chick: 其中的 **項目** 在我們點擊刪除按鈕的時候已被pass進去 :baby_chick: 需要使用 **.data()** 來轉換該項目的完整object :baby_chick: 並且將 **activeItemId** 修改成 **當前編輯的項目id** ```javascript= methods:{ editProduct(product){ this.product = product.data() $('#editModal').modal('show'); this.activeItemId = product.id } } ``` ## update firestore 更新雲端資料 > :baby_chick: 在跳出的modal的儲存按鈕加上點擊事件 **@click="updateProduct()"** ```vue= <button @click="updateProduct()" type="button"> Save changes </button> ``` :baby_chick: **db.collection('雲端儲存名稱').doc(項目ID).update(更新內容)** ```javascript= methods:{ eupdateProduct(){ db.collection('products') .doc(this.activeItemId) .update(this.product) .then(() => { $('#editModal').modal('hide'); console.log('Successfully update')} ) .catch((err) => console.log(err)) } } ``` ## watcher() 偵聽 ## onSnapShot realtime更新本地資料 > :baby_chick: 在 methods 加上 **watcher()** 使用 **db.collection('雲端儲存名稱').onSnapShot()** :baby_chick: 先清空原本的 **allproducts:[] array** 並且將新加入的doc都push進去 ```javascript= watcher(){ db.collection('products').onSnapshot((querySnapshot) => { this.allproducts = []; querySnapshot.forEach((doc) => { this.allproducts.push(doc) }) }) } ``` :baby_chick: 將 **this.watcher()** 加入updateProduct()中 偵測有改變的時候立即更新本地資料 ```javascript= updateProduct(){ db.collection('products') .doc(this.activeItemId) .update(this.product) .then(() => { $('#editModal').modal('hide'); //加入watcher偵測有改變的時候立即更新本地資料 this.watcher() console.log('更新成功')} ) .catch((err) => console.log(err)) } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up