Sometimes, we want to call function on child component on parent events with Vue.js.
In this article, we’ll look at how to call function on child component on parent events with Vue.js.
How to call function on child component on parent events with Vue.js?
To call function on child component on parent events with Vue.js, we can assign the ref to the child component and then call the method in the parent when the event is emitted.
For instance, we add
<div id="app">
<child-component ref="childComponent"></child-component>
<button @click="click">Click</button>
</div>
to add a template with the child-component
added.
We assign a ref to it.
And we call click
when we click the button by adding @click="click"
.
Next, we write
const ChildComponent = {
template: "<div>{{value}}</div>",
data() {
return {
value: 0,
};
},
methods: {
setValue(value) {
this.value = value;
},
},
};
new Vue({
el: "#app",
components: {
"child-component": ChildComponent,
},
methods: {
click() {
this.$refs.childComponent.setValue(2);
},
},
});
to add the click
method that calls this.$refs.childComponent.setValue
to call setValue
in child-component
when we click on the button.
Conclusion
To call function on child component on parent events with Vue.js, we can assign the ref to the child component and then call the method in the parent when the event is emitted.