如何使用vuexfire从Firestore数据库获取数据?

问题描述

我正在使用以下数据模型编写聊天应用程序:

database image

使用以下方法: store / index.js

 actions: {
bindMessages: firestoreAction(({ state,bindFirestoreRef }) => {
  // return the promise returned by `bindFirestoreRef`
  return bindFirestoreRef(
    'messages',db.collection('groupchats')
  );
}),},@H_502_4@

然后我从这样的vue组件访问消息store.state:

computed: {
Messages() {
  return this.$store.state.messages;
},@H_502_4@

根据vuexfire docs。 我能够(被动地)获取整个集合的数据,但是我希望特定文档的“消息数组”(假设我知道文档ID)。我该怎么办?

解决方法

以下应该可以解决问题:

state: {
    // ...
    doc: null
},mutations: vuexfireMutations,getters: {
   // ...
},actions: {
    bindDoc: firestoreAction(({ bindFirestoreRef }) => {
        return bindFirestoreRef('doc',db.collection('groupchats').doc('MI3...'))
    })
}

您可以使其动态化,如下所示:

组件:

// ...
<script>
export default {
  created() {
    this.$store.dispatch('bindDoc',{ id: '........' }); // Pass the desired docId,e.g. MI3...
  },};
</script>
// ...

Vuex商店:

state: {
    // ...
    doc: null
},getters: {
  // ...
},actions: {
    bindDoc: firestoreAction(({ bindFirestoreRef },payload) => {
        return bindFirestoreRef('doc',db.collection('groupchats').doc(payload.id));
    }),}