首页 > 解决方案 > 如何使用 vuexfire 从 firestore 数据库中获取数据?

问题描述

我正在使用以下数据模型编写聊天应用程序:数据库映像 使用以下方法:store/index.js

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

然后我从我的 vue 组件访问消息 store.state,如下所示:

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

根据vuexfire 文档。我能够(反应性地)获取整个集合的数据,但假设我知道文档 ID,我想要特定文档的 **messages 数组**。我该怎么做?

标签: firebasevue.jsgoogle-cloud-firestorevuexvuexfire

解决方案


以下应该可以解决问题:

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
},

mutations: vuexfireMutations,

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

推荐阅读