Sometimes, we want to pass data from child to parent in Vue.js.
In this article, we’ll look at how to pass data from child to parent in Vue.js.
How to pass data from child to parent in Vue.js?
To pass data from child to parent in Vue.js, we should emit an event from the child component to the parent component.
For instance, we write
this.$emit("eventname", this.variable);
to call this.$emit
with the event name and the variables we want to emit to the parent.
Then in the parent component, we write
<template>
<child-component @eventname="updateParent"></child-component>
</template>
<script>
export default {
//...
methods: {
updateParent(variable) {
this.parentvariable = variable;
},
},
//...
};
</script>
to add the child-component
in our parent component’s template.
And we listen for the eventname
event and call updateParent
when the eventname
event is emitted.
We get this.variable
that we called this.$emit
with from the variable
parameter of updateParent
.
Conclusion
To pass data from child to parent in Vue.js, we should emit an event from the child component to the parent component.