我的 Firestore 数据库中有以下集合:
我可以使用以下内容绑定(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)一个文档,你应该这样做,用
bindAssetDoc
和 assetDoc
.店铺
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/