How to call function on child component on parent events?

Technology CommunityCategory: Vue.jsHow to call function on child component on parent events?
VietMX Staff asked 3 years ago
Problem

How does a parent tell its child an event has happened via props? Should I just watch a prop called event? That doesn’t feel right, nor do alternatives (emit/on is for child to parent, and a hub model is for distant elements).

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);
    }
  }
})