Sometimes, we want to update parent data from child component with Vue.js
In this article, we’ll look at how to update parent data from child component with Vue.js.
How to update parent data from child component with Vue.js?
To update parent data from child component with 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 update parent data from child component with Vue.js, we should emit an event from the child component to the parent component.