Executing a child method from a parent component in Vue.js

I currently have Vue.js components that contain a list of other components. I know that a common way to work with vue is to pass data to children, as well as pass parent events to parents.

However, in this case, I want to execute the method in the child components when the button in the parent is clicked. What would be the best way to do this?

+8
javascript
source share
2 answers

One of the suggested methods is to use the global event center. This allows communication between any components that have access to the hub.

Here is an example showing how an event hub can be used to run a method on a child component.

var eventHub = new Vue(); Vue.component('child-component', { template: "<div>The 'clicked' event has been fired {{count}} times</div>", data: function() { return { count: 0 }; }, methods: { clickHandler: function() { this.count++; } }, created: function() { // We listen for the event on the eventHub eventHub.$on('clicked', this.clickHandler); } }); new Vue({ el: '#app', methods: { clickEvent: function() { // We emit the event on the event hub eventHub.$emit('clicked'); } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script> <div id="app"> <button @click="clickEvent">Click me to emit an event on the hub!</button> <child-component></child-component> </div> 
+4
source share

You can create a helper method below in the methods of the parent component:

 getChild(name) { for(let child of this.$children) if (child.$options.name==name) return child; }, 

And call the method of child components as follows:

 this.getChild('child-component-tag-name').childMethodName(arguments); 

I do not test it for Vue> = 2.0

0
source share

All Articles