将onSnapshot firestore中的数据分配给Vue ref变量时出现问题



我和我的朋友正在使用Vue与firestore创建一些功能。这是我们第一次使用这两种产品,我们遇到了一些麻烦。我们现在正在尝试添加onSnapshot到firestore上的文档并分配说数据到一个value ref变量,从而可以使用监视器并响应更改。

从图片中可以看出,我们的文档包含2个数组,这是我们需要在onSnapshot观察到变化后到达的数据。我们的问题是,我们不知道如何将gameData分配给适当的数据,以便我们能够到达并使用函数外部的观察者。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
}

最新更新