firebase - Vuexfire 将 Firestore 集合绑定(bind)到对象而不是列表

标签 firebase vue.js google-cloud-firestore vuefire vuexfire

我的 Firestore 数据库中有以下集合:

scheme

我可以使用以下内容绑定(bind)到我的 vuex 商店:

state: {
  assets: [],
},

actions: {
  bindAssets: firestoreAction(({ bindFirestoreRef }) => {
    return bindFirestoreRef('assets', db.collection('assets'))
  }),
},

然而,这将它们绑定(bind)到 assets作为列表,即

[
  {id: "id1" /* etc. */ },
  {id: "id2" /* etc. */ },
  {id: "id3" /* etc. */ },
]

在哪里,我希望它被绑定(bind)为:

{
  "id1": { /* etc. */ },
  "id2": { /* etc. */ },
  "id3": { /* etc. */ },
}

我怎样才能做到这一点?

最佳答案

如果要改造assets数组(通过绑定(bind) assets 集合获得)在一个对象中,如下所示

{
  "id1": { /* etc. */ },
  "id2": { /* etc. */ },
  "id3": { /* etc. */ },
}
以下 Vuex getter 应该可以解决问题:
state: {
  assets: [],
},

actions: {
  bindAssets: firestoreAction(({ bindFirestoreRef }) => {
    return bindFirestoreRef('assets', db.collection('assets'))
  }),
},

getters: {
     assetsObj: state => {

         const arrayToObject = (array) =>
            array.reduce((obj, item) => {
                 obj[item.id] = item
                 return obj
            }, {})

        return arrayToObject(state.assets)

    }
}

更新您的评论(在聊天中):
如果你只想绑定(bind)一个文档,你应该这样做,用bindAssetDocassetDoc .
店铺
state: {
    assets: [],
    assetDoc: null
},

mutations: vuexfireMutations,

actions: {
    bindAssetDoc: firestoreAction(({ bindFirestoreRef }, payload) => {
        return bindFirestoreRef('assetDoc', db.collection('assets').doc(payload.id))
    }),
    bindAssets: firestoreAction(({ bindFirestoreRef }) => {
        return bindFirestoreRef('assets', db.collection('assets'))
    })
}
COMPONENT开通通过/asset/:assetId
<script>
//...
export default {
  created() {
    console.log('OK1');
    this.$store
      .dispatch('bindAssetDoc', { id: this.$route.params.assetId });
  }
};
</script>

关于firebase - Vuexfire 将 Firestore 集合绑定(bind)到对象而不是列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61097916/

相关文章:

java - ClassNotFoundException 没有找到类“com.google.android.gms.common.internal.zzbq

listview - NativeScript Angular 2 Firebase 列表不起作用

javascript - 返回对象的 Firebase 查询

javascript - 引用错误: __dirname is not defined in ES module scope building script

css - 仅滚动一个 flexbox 元素,而另一个使用 flex-column 保持固定

javascript - 如何获取 Firestore 查询中的第二个 10 文档?

javascript - rxjs firstValueFrom() 永远不会取消订阅 observavble

javascript - 如何从对象数组中的嵌套数组中获取数组值的组合

reactjs - 通过在本地保存数据并将其与 Firestore 中的数据进行比较来减少 Firestore 读取?

firebase - 如何在Firestore -Flutter中将所有文档从一个集合复制到另一个?