【发布时间】:2021-11-04 08:46:50
【问题描述】:
如何从子集合中获取所有的 cmets?
这是我获取 cmets 集合的可重用函数。
import { ref, watchEffect } from 'vue';
import { projectFirestore } from '../firebase/config';
const getCollection = (collection, id, subcollection) => {
const comments = ref(null);
const error = ref(null);
// register the firestore collection reference
let collectionRef = projectFirestore
.collection(collection)
.doc(id)
.collection(subcollection);
const unsub = collectionRef.onSnapshot(
snap => {
let results = [];
snap.docs.forEach(doc => {
doc.data().createdAt && results.push(doc.data());
});
// update values
comments.value = results;
error.value = null;
},
err => {
console.log(err.message);
comments.value = null;
error.value = 'could not fetch the data';
}
);
watchEffect(onInvalidate => {
onInvalidate(() => unsub());
});
return { error, comments };
};
export default getCollection;
这是我的 Comments.vue,我在 setup() 函数(组合 API)中传递参数
const { comments } = getAllComments('posts', props.id, 'comments');
当我 console.log(cmets) 它的 null 时,在快照中 doc.data() 很好,但不知何故,即使我将 doc.data() 推送到结果数组并将其传递给 cmets.value,结果也是空数组。
有人可以帮我如何获得该子集合吗?
这是我的 Comment.vue 组件
export default {
props: ['id'],
setup(props) {
const { user } = getUser();
const content = ref('');
const { comments } = getAllComments('posts', props.id, 'comments');
const ownership = computed(() => {
return (
comments.value && user.value && user.value.uid == comments.value.userId
);
});
console.log(comments.value);
}
return { user, content, handleComment, comments, ownership };
}, };
【问题讨论】:
-
getAllComments()定义在哪里? -
@Dharmaraj 我为可重用函数(firebase 函数)创建了可组合文件夹,以获取集合、发布集合、获取单个文档等。
-
您能否用完整的代码更新您的问题,以便我们查看该函数的作用?
-
@Dharmaraj 这是我的函数所做的,变量 projectFirebase 是 firebase.firestore();我的函数需要参数,在 Comments.vue 中我导入这个文件,如 import getAllComments.js from '@/composables/getAllComments' 和在设置函数中我销毁 const {cmets} 中的 cmets 并使用 REAL 参数调用函数。我希望你能理解我,我的英语不好,谢谢
-
@PeterO。它的工作原理是这样的
标签: firebase vue.js google-cloud-firestore vue-composition-api