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.
If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.
You can use $emit
and $on
. Using @RoyJ code:
html:
<div id="app"> <my-component></my-component> <button @click="click">Click</button> </div>
javascript:
var Child = { template: '<div>{{value}}</div>', data: function () { return { value: 0 }; }, methods: { setValue: function(value) { this.value = value; } }, created: function() { this.$parent.$on('update', this.setValue); }}new Vue({ el: '#app', components: { 'my-component': Child }, methods: { click: function() { this.$emit('update', 7); } }})
Running example: https://jsfiddle.net/rjurado/m2spy60r/1/