【问题标题】:How to get the number of Vue components rendered in the DOM?如何获取 DOM 中渲染的 Vue 组件的数量?
【发布时间】:2020-07-29 13:30:17
【问题描述】:

我正在构建一个带有 firestore 后端的博客应用程序,并且我在一个组件中展示了我从 firestore 带来的 cmets,该组件针对每条评论重复......到目前为止一切都很好。

现在想知道cmets的集合中有多少个cmets,问题是不建议带集合的大小querySnapshot.size,因为它读取整个集合,另一种方法是使用分布式计数器,但是对于我这样的菜鸟来说,它们是一件很痛苦的事情......此外,我不打算接受这么多的cmets来使用柜台。

那么,有没有办法获取 DOM 中呈现的组件数量?这样,我就不必计算集合中有多少 cmets,因为我已经在 DOM 中打印了总 cmets。

【问题讨论】:

  • 如果您已经将所有 cmets 渲染到 HTML 中,那么您已经从数据库中加载了所有 cmets,不是吗?在那种情况下,你为什么不直接在快照中调用size
  • @FrankvanPuffelen 不认为那是对整个收藏的再次阅读吗?
  • 如果您已经拥有querySnapshot,则不会。您为查询快照的构建付费,而不是为调用快照付费。
  • 完美,谢谢。

标签: javascript firebase vue.js google-cloud-firestore vue-component


【解决方案1】:

如前所述,您可以使用 querySnapshot 中的size,它不会对集合进行额外读取,因为它只是已检索文档的数量。

另一种方法是计算组件已安装和更新的次数,显示如何操作的想法here

<div id="app">
  <div>
    <p>Number of comments {{comments}}</p>
    <comments-component></comments-component>
    <comments-component></comments-component>
    <comments-component></comments-component>
  </div>
  <br>
</div>
Vue.component('comments-component', {
  template: '<p>Comment</p>'
})
new Vue({
  el: '#app',
  data: {
    comments: 0
  },
  methods: {
    updateCommmentCounter() {
      this.comments = this.$children.filter(child => child.constructor.options.name === 'comments-component').length;
    }
  },
  beforeUpdate() {
    this.updateCommmentCounter()
  },
  mounted() {
    this.updateCommmentCounter()
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 2015-11-03
    • 2018-10-19
    • 2018-05-04
    • 2018-01-25
    • 2018-05-30
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多