将数据从 onSnapshot firestore 分配给 Vue ref 变量时出现问题
Problem assigning data from onSnapshot firestore to a Vue ref variable
我和我的朋友们正在使用 Vue 和 firestore 来创建一些功能。
这是我们第一次使用其中任何一个,我们遇到了一些麻烦。
我们现在正在尝试将 onSnapshot 添加到 firestore 上的文档并分配说
数据到 vue ref 变量,从而可以使用观察者并响应变化。
如图所示,我们的文档包含 2 个数组,这是我们在 onSnapshot 观察到更改后需要获取的数据。我们的问题是我们不知道如何将 gameData 分配给适当的数据,以便我们可以在函数外部访问和使用观察者。
Datastructure on firestore
export function realTimeGame(lobbyId) {
const gameCollection = firestore.collection('lobbies/' + lobbyId + '/game_data');
const gameData = ref([]);
const unsubscribe = gameCollection.doc('gameThings').onSnapshot(snapshot => {
// gameData.value = snapshot.map(document => ({ id: document.id, ...document.data() })) .map is not defined
gameData.value = snapshot; //this is essentially what we want to do
});
onUnmounted(unsubscribe)
return { gameData }
}
我们找到了解决方案:
export function realTimeGame(lobbyId) {
const gameData = ref();
const unsub = onSnapshot(doc(firestore,'lobbies/' + lobbyId + '/game_data/gameThings'),(doc) => {
gameData.value = { ...doc.data()}
})
onUnmounted(unsub)
return gameData
}
我和我的朋友们正在使用 Vue 和 firestore 来创建一些功能。 这是我们第一次使用其中任何一个,我们遇到了一些麻烦。 我们现在正在尝试将 onSnapshot 添加到 firestore 上的文档并分配说 数据到 vue ref 变量,从而可以使用观察者并响应变化。
如图所示,我们的文档包含 2 个数组,这是我们在 onSnapshot 观察到更改后需要获取的数据。我们的问题是我们不知道如何将 gameData 分配给适当的数据,以便我们可以在函数外部访问和使用观察者。 Datastructure on firestore
export function realTimeGame(lobbyId) {
const gameCollection = firestore.collection('lobbies/' + lobbyId + '/game_data');
const gameData = ref([]);
const unsubscribe = gameCollection.doc('gameThings').onSnapshot(snapshot => {
// gameData.value = snapshot.map(document => ({ id: document.id, ...document.data() })) .map is not defined
gameData.value = snapshot; //this is essentially what we want to do
});
onUnmounted(unsubscribe)
return { gameData }
}
我们找到了解决方案:
export function realTimeGame(lobbyId) {
const gameData = ref();
const unsub = onSnapshot(doc(firestore,'lobbies/' + lobbyId + '/game_data/gameThings'),(doc) => {
gameData.value = { ...doc.data()}
})
onUnmounted(unsub)
return gameData
}