gpt4 book ai didi

javascript - NuxtJS 和 Firebase Web SDK Beta v9 : How to add realtime listener to firestore?

转载 作者:行者123 更新时间:2023-12-04 17:15:13 25 4
gpt4 key购买 nike

我将新的 Firebase Web SDK v9(测试版 8)与 NuxtJS2 一起使用。我有一个子组件,允许用户编辑他的帖子数据。这会使用新的帖子更改更新 Firestore 中的文档。但是,我的问题是……如何让我的父组件实时更新这些新数据?

让我解释一下:

我在应用程序中有以下示例组件结构:

<PostCardDetail>
<PostEdit />
</PostCardDetail>

PostCardDetail.vue 我正在执行数据获取的脚本部分:

import { doc, getDoc } from 'firebase/firestore'
import { mapGetters } from 'vuex'
import { db } from '~/plugins/firebase'
export default {
name: 'PostCardDetail',
data() {
return {
post: {}
}
},
async fetch() {
const docRef = doc(db, 'posts', this.$route.params.postId)
const docSnap = await getDoc(docRef)
this.post = docSnap.data()
},
mounted () {
// I believe I will need to mount the realtime listener here?
},
}
</script>

我正在执行数据编辑的 PostEdit.vue 脚本部分:

editPost() {
const postRef = doc(db, 'posts', this.post.id)
await updateDoc(postRef, {
...editedPost,
updatedAt: serverTimestamp()
})
console.log('updated!')
this.$store.dispatch('edit', false)
alert('Post successfully updated!')
}

我能够成功编辑数据,但是要查看最新的变化,我需要手动刷新浏览器。用户编辑帖子后,如何使用 firestore 获得自动实时更新?我假设此监听器将位于 PostCardDetail?

的 mounted() Hook 属性中

我的尝试:

  mounted() {
// eslint-disable-next-line no-unused-vars
const unsub = onSnapshot(
doc(db, 'posts', this.$route.params.postId),
(snapshot) => {
this.post = snapshot.data()
}
)
}

这看起来工作正常,但感觉有点笨拙。这是使用 NuxtJS 解决此问题的推荐方法吗?

最佳答案

查询看起来非常好,与 documentation 中提到的相似.

I assume this listener will be in the mounted() hook property of PostCardDetail

理想情况下,您可能希望在创建组件后设置监听器,我经常看到监听器是在 created()

中设置的
created() {
const unsub = onSnapshot(
doc(db, 'posts', this.$route.params.postId),
(snapshot) => {
this.post = snapshot.data()
}
)
}

要在其他地方使用 unsub,您可以根据您的用例在数据属性中设置它或将其传递给其他组件。

关于javascript - NuxtJS 和 Firebase Web SDK Beta v9 : How to add realtime listener to firestore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68847519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com