Vue: How to check the type of children component?

Created on 2 Dec 2015  ·  6Comments  ·  Source: vuejs/vue

Hi,

I want to do something like:
The parent component displays the number of its children components of a specific type.
An example:

// Should display 3
<Parent>
  <div>{{ numOfChildComponents }}</div>
  <Child></Child>
  <Child></Child>
  <Hello></Hello>
  <Child></Child>
</Parent>

How should I achieve this?

I saw an implementation to assign a specific class to the children,
and then in the parent component it uses jQuery to find out the children of that class.
This works but I'm wondering if there is less jQuery or DOM approach to achieve this?

Most helpful comment

For reference...
this.$children[n].constructor.options.name

All 6 comments

Use an Array to drive your child components:

<Child v-for="n in childCount></Child>

What if the children are dynamics?

Say a carousel component that lets developer put Child component inside dynamically?

That's what he is telling you to do

Use an array to keep track of the children.

They will be dynamically tracked that way.

If you don't understand this try playing around in the js console a bit
more.

On Wed, Dec 2, 2015, 4:36 PM Yifeng [email protected] wrote:

What if the children are dynamics?

Say a carousel component that lets developer put Child component inside
dynamically?


Reply to this email directly or view it on GitHub
https://github.com/vuejs/vue/issues/1953#issuecomment-161478186.

For reference...
this.$children[n].constructor.options.name

For me I had to use:

this.$children[n].$options._componentTag

Which I then coupled with:

```JavaScript
this.$children.filter(c => c.$options._componentTag === 'custom-tag');
````

To directly get the number count of _Child_ components based on their component name, you can use the return value of this function for your variable numOfChildComponents:

this.$children.reduce((total, child) => total + (child.$options.name === 'Child'), 0)

Array method reduce() does the following here:

  1. Start with 0
  2. Loop over every item in $children
  3. Name match? Add 1 to total, otherwise 0.
  4. Carry running total to evaluation of next child item
  5. Return final total
Was this page helpful?
0 / 5 - 0 ratings