Reputation: 1526
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?
Upvotes: 4
Views: 1366
Reputation: 20299
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.
Upvotes: 1
Reputation: 6912
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
Upvotes: 0
Reputation: 3403
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.
Upvotes: 1
Reputation: 904
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');
}
Upvotes: 0