Home > Software design >  count child components programmatically
count child components programmatically

Time:09-29

In a Vue app there is a page being developed that has multiple child components. Each child emits an event to the parent. Here is a code snippet of a few components in the template:

<warehouses-01 @component-loaded="() => this.componentsLoaded.push('warehouses-01')" />
<warehouses-03 @component-loaded="() => this.componentsLoaded.push('warehouses-03')" />
<warehouses-04 @component-loaded="() => this.componentsLoaded.push('warehouses-04')" />
<warehouses-07 @component-loaded="() => this.componentsLoaded.push('warehouses-07')" />

Related code in the script tags -

export default {
    watch: {
        componentsLoaded() {
            if (this.componentsLoaded.length === 4) this.isLoaded = true;
        }
    },
    data() {
        return {
            componentsLoaded: [],
            isLoaded: false
        }
    }
}

When the isLoaded property becomes true then other code (not shown above) takes action. The issue is that when new child components get added the hard coded value within the watcher needs to be updated manually. I have forgotten this manual update step multiple times and then wonder why the page isn't behaving as expected. To eliminate this step - is there a way to programmatically count the number of child components or, better yet, count the number of child components that emit the "component-loaded" event?

CodePudding user response:

This could be a solution:

watch: {
    componentsLoaded() {
        let componentCounter = this.$children.filter( i => i.$listeners['component-loaded'] ).length;
        if (this.componentsLoaded.length === componentCounter) this.isLoaded = true;
    }
},
  • Related