【问题标题】:Vuexfire {serialize} option not formatting array properlyVuexfire {serialize} 选项未正确格式化数组
【发布时间】:2020-12-27 14:08:49
【问题描述】:

我在查询集合时尝试添加所有 Firestore 文档 ID。我可以查询一个实例中的所有集合,但不能将它们的文档 ID 绑定到集合数组。

这是我拥有的用于在名为 product.js 的 vuex 文件中查询所有用户产品的代码

import { firestoreAction } from 'vuexfire'
import { db } from '@/firebase/init'

const state = {
  products: []
}

const getters = {}

const actions = {
  init: firestoreAction( context  => {
    const allProducts = db.collection(`users/${context.rootState.authentication.user.uid}/products`)
    context.bindFirestoreRef(
      'products',
      allProducts, { 
        wait: true, 
        serialize: doc => {
          // console.log(doc.id) -returns the IDS I am looking for
          return Object.defineProperty(doc.data(), 'id', {
            value: doc.id
          })
        }
      }
    )
  })
}

然后我得到这个数据

[
   {
      "name":"product1"
   },
   {
      "name":"product2"
   }
]

我希望像这样将数据传递给 vuex:

[
   {
      "id":"kmp1Ue8g0I130XZ3Ttqd",
      "name":"ll"
   },
   {
      "id":"qswtcdmnxNxbwmPNR1S3",
      "name":"fdsfs"
   }
]

当我使用console.log(doc.id) 时,会显示上述 id,但我没有得到具有 id 值的预期数组,只是产品 姓名

【问题讨论】:

    标签: firebase vue.js vuex vuefire vuexfire


    【解决方案1】:

    这是因为你不能修改doc.data()返回的Object。

    以下,使用对象扩展运算符创建一个新的普通对象,应该可以解决问题:

    return {
       id: doc.id,
       ...doc.data()
     }
    

    【讨论】:

    • 工作就像一个魅力!非常感谢
    猜你喜欢
    • 2014-05-27
    • 2023-04-04
    • 1970-01-01
    • 2017-08-17
    • 2021-04-24
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多