在 ionic vue 應用程式中,我想顯示來自 Firebase Firestore 的一些資料。
在 Firestore 中,我有一個households帶有子集合的集合entries。用戶可以是一個家庭的成員,我想顯示她所屬的所有家庭的所有條目。
我有一個陣列entries在我的data:
data() {
return {
entries: [],
};
},
我通過對 firebase 進行三個嵌套查詢來填充這個陣列:
- 獲取當前用戶
- 獲取與當前用戶關聯的所有家庭
- 獲取當前用戶所有家庭的所有條目
beforeCreate: function () {
auth.onAuthStateChanged((user) => {
if (user) {
// Get current uid
let uid = user.uid;
// Loop trough all households of user
let userHouseholdIds = [];
db.collection("households")
.where("members", "array-contains", uid)
.onSnapshot((snapshotChange) => {
snapshotChange.forEach((doc) => {
userHouseholdIds.push(doc.id);
});
userHouseholdIds.forEach((householdId) => {
// Get household name
db.collection("households")
.doc(householdId)
.get()
.then((value) => {
let householdId = value.id;
let householdName = value.data().name;
// Get household entries
db.collection("households")
.doc(householdId)
.collection("entries")
.onSnapshot((snapshotChange) => {
snapshotChange.forEach((doc) => {
let newDoc = doc.data();
newDoc["id"] = doc.id;
newDoc["householdName"] = householdName;
newDoc["householdId"] = householdId;
this.entries.push(newDoc);
});
});
});
});
});
}
});
雖然我不確定這是否是要走的路,但這按預期作業(到目前為止)。
但是,當我直接在 Firestore 控制臺e1中對家庭中的條目進行更改時,前端中的h1每個條目h1都會重復。
我想,this.entries = []在 Firestore 的更新進來之前,我需要一個地方,但我不知道在哪里。
我在正確的軌道上嗎?我需要修改什么以避免重復?非常感謝!
uj5u.com熱心網友回復:
如果您必須使用“onSnapshot”檢查 change.type
db
.collection(...)
.where(...)
.onSnapshot((snapshotChange) => {
snapshotChange.docChanges().forEach(change => {
if (change.type === 'added') {
this.entries.push()
} else if (change.type === 'modified') {
this.entries.splice()
} else if (change.type === 'removed') {
this.entries.splice()
}
})
})
如果沒有,請嘗試使用 get()
db
.collection(...)
.where(...)
.get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364342.html
