我onSnapshot在 Nuxt3 應用程式的組件中使用 Firestore 偵聽器。我想知道當組件未安裝時如何分離偵聽器。如何成功分離監聽器?我想我可以在鉤子里打電話給unsubscribe聽眾?onUnMounted
onMounted()我已經在一個分離的鉤子中設定了監聽器,如下所示:
<script setup>
import { useUserStore } from '@/stores/user'
import {
onSnapshot,
collection,
query,
where,
getDocs
} from 'firebase/firestore'
const userStore = useUserStore()
const loading = ref(false)
const userPosts = reactive([])
const unsubscribe = ref(null)
onMounted(async () => {
const { firestore } = useFirebase()
const userPostsRef = collection(firestore, 'posts')
const q = query(userPostsRef, where('uid', '==', userStore.userProfile.uid))
unsubscribe.value = onSnapshot(q, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
console.log('added', change.doc.data())
userPosts.push(change.doc.data())
}
if (change.type === 'modified') {
console.log('modified', change.doc.data())
userPosts.splice(
userPosts.findIndex((post) => post.id === change.doc.id),
1,
change.doc.data()
)
}
if (change.type === 'removed') {
console.log('removed', change.doc.data())
userPosts.splice(
userPosts.findIndex((post) => post.id === change.doc.id),
1
)
}
})
})
loading.value = false
})
onUnmounted(() => {
unsubscribe.value //<-----is this the correct way to detach it?
})
編輯:我剛剛確認上述方法不會洗掉偵聽器,因為每次我離開頁面時,我都會得到('add','modified'等)的控制臺日志。所以,我一定做錯了什么。
uj5u.com熱心網友回復:
這unsubscribe是一個函式,所以你必須呼叫它,如下所示:
onUnmounted(() => {
// call only when unsubscribe is not null
unsubscribe.value && unsubscribe.value()
// or use optional chaining
unsubscribe.value?.();
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/489794.html
標籤:javascript 火力基地 谷歌云火库 nuxt3
