[英]problem getting id and deleting document Vuejs Firestore
我正在為我的商店創建網站並同時學習 Vue js。 我在從 Firestore 獲取產品 ID 並能夠刪除產品時遇到問題。 當我在控制台 ID 中創建新產品時,也沒有出現此消息(使用 ID 編寫的文檔:未定義)我正在使用 Vue js 3 和 Firebase 9
我在 main.j 上有這個
const dataBase = collection(db, "products");
這在 products.js
<script>
import { dataBase } from '../main';
import { addDoc, onSnapshot, doc, deleteDoc } from "firebase/firestore";
export default {
name: "Products",
props: {
msg: String
},
data() {
return {
products: [],
product: {
name: '',
detail: '',
price: '',
brand: '',
category: ''
}
}
},
methods: {
saveData() {
try {
const docRef = addDoc(dataBase, this.product);
console.log("Document written with ID: ", docRef.id);
this.reset();
} catch (e) {
console.error("Error adding document: ", e);
}
},
reset() {
Object.assign(this.$data, this.$options.data.apply(this));
},
deleteProduct(doc) {
deleteDoc(doc(dataBase, doc.id));
}
},
created() {
onSnapshot(dataBase, (snapshot) => {
snapshot.docs.forEach((doc) => {
this.products.push({ ...doc.data(), id: doc.id })
})
});
}
};
</script>
“使用 ID 編寫的文檔:未定義” output 是因為addDoc
function是異步操作,因此返回Promise<DocumentReference>
。 您必須await
其結果,或使用then
:
addDoc(dataBase, this.product).then((docRef) => {
console.log("Document written with ID: ", docRef.id);
this.reset();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.