Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing child method from parent component in Vue.js

Currently, I have a Vue.js components which contains a list of other components. I know that the common way of working with vue is passing data to children, and emitting events to parents from children.

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

like image 522
angrykoala Avatar asked Nov 28 '16 23:11

angrykoala


People also ask

How do you access the child component property in the parent component Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do you call parent to child components?

Call Child Component method from Parent Component A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular.


3 Answers

Here is a simple one which worked for me

this.$children[indexOfComponent].childsMethodName();
like image 143
Pratik Khadtale Avatar answered Oct 20 '22 04:10

Pratik Khadtale


One suggested way is to use a global event hub. 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 fire 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>
like image 37
asemahle Avatar answered Oct 20 '22 03:10

asemahle


You can create below helper method in methods in your parent component:

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

And call child component method in this way:

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

I don't test it for Vue>=2.0

like image 43
Kamil Kiełczewski Avatar answered Oct 20 '22 04:10

Kamil Kiełczewski