Vuexfire 将 Firestore 集合绑定到 Object 而不是 List

Posted

技术标签:

【中文标题】Vuexfire 将 Firestore 集合绑定到 Object 而不是 List【英文标题】:Vuexfire bind Firestore collection to Object instead of a 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”(我已经更新了我的问题) 【参考方案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 []
,

【讨论】:

以上是关于Vuexfire 将 Firestore 集合绑定到 Object 而不是 List的主要内容,如果未能解决你的问题,请参考以下文章

Vuexfire serialize 选项未正确格式化数组

Firestore、vue、vuex、vuexfire:如何让 getter 真正从存储中获取数据?

使用 vuexfire 动态绑定 firebase 集合列表

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

为啥 vuexfire 不更新状态而是正确更新 ui?

将用户绑定到 Firestore 集合的正确方法?