从Firestore集合获取包含ID的文档

3
在使用Firestore、vuefire和vue-tables-2时,我遇到了获取文档ID的问题。
我的数据结构如下所示。 enter image description here
  <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 文档中所述。

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

enter image description here enter image description here

1个回答

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

Vuexfire 绑定的任何文档都将保留其在数据库中的 id 作为非可枚举的只读属性。这样可以更轻松地编写更改,并允许您仅使用扩展运算符或 Object.assign 复制数据。

您可以直接使用 device.id 访问 id。但当传递给 vue-tables-2、设备被复制并且失去了 id 非可枚举属性。

我认为可以使用 computed 属性绕过此问题。

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

那么,请尝试在vue-tables-2中使用devicesWithId

谢谢您的回答。请问您能告诉我如何传递新的 deviceWithId 吗?代码如下:return this.devices.map(device => { let newDevice = {}; newDevice = Object.assign({}, device); newDevice.id = device.id; newDevices.push(newDevice)}。我已经检查了 device.id,它有文档 ID。但是我卡在了如何传递这些参数上。 - sungyong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接