How to call function on child component on parent events How to call function on child component on parent events vue.js vue.js

How to call function on child component on parent events


Give the child component a ref and use $refs to call a method on the child component directly.

html:

<div id="app">  <child-component ref="childComponent"></child-component>  <button @click="click">Click</button>  </div>

javascript:

var ChildComponent = {  template: '<div>{{value}}</div>',  data: function () {    return {      value: 0    };  },  methods: {    setValue: function(value) {        this.value = value;    }  }}new Vue({  el: '#app',  components: {    'child-component': ChildComponent  },  methods: {    click: function() {        this.$refs.childComponent.setValue(2.0);    }  }})

For more info, see Vue documentation on refs.


What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would watch that prop. When the child takes action, it notifies the parent via an emit, and the parent might then change the state again.