4

Lets say component name is "customComponent"

and its usage example:

<custom-component class='parent'>
  <div v-if='someTruthyCondition'>
    <custom-component class='child'></custom-component>
  </div>
</custom-component>

Lets assume, the 'someTruthyCondition' is true util 3 components get generated and recursion stops.

I would like to know how to communicate between the child customComponent to parent customComponent in vue js?

4 Answers 4

1

You can use functions as props in Vue.js. It’s not a common pattern because, unlike with React, Vue.js has custom events for child-to-parent communication. But for cases like this one it really comes in handy.

Unlike emitting events at each level, this is much simpler and performant since we only need to pass down the same reference to the function.

Check this out.

Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure if this will work since your example feels like a code-smell, and I have not tried something like this. You could use events and whenever a child component is created you could emit an event to your parent:

https://v2.vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events

In the example from the Vue.js docs they use this:

<button-counter v-on:increment="incrementTotal"></button-counter>

So the child components call this inside the created lifecycle hook:

this.$emit('increment')

Whenever you receive this event inside your parent, you could just increment a number and when it reaches 3 your stop your v-for loop.

<custom-component class='child'></custom-component>

Granted I have no idea if this will even work, but on the top of my head this is something I came up with.

1 Comment

Could you please provide me a fiddle. I tried to write the code, but missing the answer to my question.
0

I haven't tested this but I think something like this may help you.

main.js:

window.Event = new Vue();

Parent element:

mounted () {
    Event.$on('recursion', () => {
        this.recursion++;
    })
}

Child elements:

created () {
    Event.$emit('recursion');
}

2 Comments

unable to figure out what you have mentioned. Fiddle would be helpful
@NitinKumar Look up "Vue.JS Event Bus"
0

Use v-on="$listeners" to recursive child to trigger the event to parent.

When you attach any any event listener to first call of a component, then this way you can attach to all recursive call components.

<custom-component class='parent' @click="doSomething()">
  <div v-if='someTruthyCondition'>
    <custom-component class='child' v-on="$listeners"></custom-component>
  </div>
</custom-component>

Now in your component where you are consuming it, there will be doSomething method - and it will get triggered to any of the recursive child

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.