首页 > 解决方案 > 从 firstore 集合中获取带有 ID 的文档

问题描述

在使用 Firestore、vuefire、vue-tables-2 时,我一直在获取文档的 ID。

我的数据结构如下。 在此处输入图像描述

这是我的代码。

  <v-client-table :columns="columns" :data="devices" :options="options" :theme="theme" id="dataTable">


 import { ClientTable, Event } from 'vue-tables-2'
  import { firebase, db } from '../../firebase-configured'

  export default {
    name: 'Devices',
    components: {
      ClientTable,
      Event
    },
    data: function() {
      return {
        devices: [],
        columns: ['model', 'id', 'scanTime', 'isStolen'],
        options: {
          headings: {
            model: 'Model',
            id: 'Serial No',
            scanTime: 'Scan Time',
            isStolen: 'Stolen YN'
          },
          templates: {
            id: function(h, row, index) {
                return index + ':' + row.id  // <<- row.id is undefined
            },
            isStolen: (h, row, index) => {
                return row.isStolen ? 'Y': ''
            }
          },
          pagination: {
            chunk: 5,
            edge: false,
            nav: 'scroll'
          }
        },
        useVuex: false,
        theme: 'bootstrap4',
        template: 'default'
      }
    },
    firestore: {
        devices: db.collection('devices')
    },
  };

我的期望是设备应该id属性为vuefire docs

但是即使我检查它是否存在它控制台,数组this.devices也没有字段。id

在此处输入图像描述 在此处输入图像描述

标签: vue.jsgoogle-cloud-firestorevuefirevue-tables-2

解决方案


基本上,每个文档都已经有id属性,但它是不可枚举的

任何被 Vuexfire 绑定的文档都会在数据库中保留它的 id 作为不可枚举的只读属性。这使得编写更改更容易,并允许您仅使用扩展运算符或 Object.assign 复制数据。

您可以id直接使用device.id. 但是当传递给vue-tables-2、设备时,会被复制并丢失id不可枚举的属性。

我认为您可以使用computed属性来解决

computed: {
  devicesWithId() {
    if (!this.devices) {
      return []
    }
    return this.devices.map(device => {
      ...device,
      id: device.id
    })
  }
}

然后,请尝试devicesWithId在 vue-tables-2 中使用。


推荐阅读