vue.js - 从 firestore 集合中获取带有 ID 的文档

标签 vue.js google-cloud-firestore vuefire vue-tables-2

在使用 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 docs .

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

enter image description here enter image description here

最佳答案

基本上,每个文档都有id 属性,但它是non-enumerable

Any document bound by Vuexfire will retain it's id in the database as a non-enumerable, read-only property. This makes it easier to write changes and allows you to only copy the data using the spread operator or Object.assign.

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

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

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

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

关于vue.js - 从 firestore 集合中获取带有 ID 的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55895823/

相关文章:

angular - 空注入(inject)器错误 : No provider for AngularFirestore

swift - 有没有一种方法可以将 GeoFireStore 查询与普通的 Firestore 查询结合起来?

javascript - Vuejs 3 createApp 使用来自 vuefire 的 firestorePlugin 获取 Uncaught TypeError : Cannot set property '$unbind' of undefined and no render

javascript - 我如何使用 VueFire 将 prop 作为 firebase 路径的一部分?

javascript - Vue js 在编译时删除脚本标签

javascript - 使用 v-for 填充 vue 中的多个选择菜单和选项

javascript - 在方法对象的函数内发出自定义事件

css - 背景图像在 Nuxt.js 中没有响应

firebase - Firestore监听器无法按预期工作

firebase - 在 vuex 操作中访问 this.$fireStore (Nuxt.js)