【问题标题】:Vuexfire bind Firestore collection to Object instead of a ListVuexfire 将 Firestore 集合绑定到 Object 而不是 List
【发布时间】:2020-07-20 16:49:39
【问题描述】:

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

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

state: {
  assets: [],
},

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

但是,这会将它们绑定到 assets 作为列表,即

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

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

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

我怎样才能做到这一点?

【问题讨论】:

  • 这很奇怪。我试图重现您的情况,生成的 assets 数组是对应于 data() 方法的对象数组,即没有任何 .key 属性。您使用的是特定设置吗?
  • @RenaudTarnec 这是此处记录的只读属性:vuefire.vuejs.org/vuexfire/… 我刚刚将其添加到示例中以表明它确实存储了密钥,但不是以我想要的形式。
  • 我试图了解你是如何得到这个[{.key: "id1" /* etc. */ }, ...] 数组的。你能分享一下用来获取它的代码吗?
  • @RenaudTarnec 我刚刚手写了那部分。但是你可以通过记录一个返回state.assets的getter来获得它。
  • @RenaudTarnec 实际上,我确实犯了一个错字。默认情况下它是“id”而不是“.key”(我已经更新了我的问题)

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


【解决方案1】:

如果你想将assets数组(通过绑定assets集合获得)转换成一个Object,如下所示

{
  "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)

    }
}

在您的 cmets 之后更新(在聊天中):

如果您只想绑定到一个文档,您应该执行以下操作,使用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>

【讨论】:

    【解决方案2】:

    根据 vuexfire 的offical documentation,您需要使用{} 而不是[] 来初始化您的状态

    state: {
      assets: {},  // instead of []
    },
    

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2011-07-09
      • 1970-01-01
      • 2022-07-11
      • 2011-11-17
      相关资源
      最近更新 更多