[Vuejs]-How to get the number of Vue components rendered in the DOM?

4👍

As already said, you can use size from querySnapshot, it won’t make an additional read to the collection, since it’s only the number of already retrieved documents.

Another way to do it is by counting the number of times the component has been mounted and updated an idea of how to do it is shown 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()
  }
})

Leave a comment