In this article, we will learn how to update parent data from a child component in Vuejs.
To update parent data from a child component, we will use a custom event in vue. This custom event is emitted from the child to the parent component.
We will use the $emit
function in vue component that allows us to pass custom events to its parent component.
In general, emit function notifies the parent component about changes in the child component.
Update parent data from child component using custom event
In this example, we have two components: App.vue
(Parent component) and Child.vue
(child component).
And in the parent component, we have a name data variable, which we want to change when we click the button in the Child.vue
component
Child.vue
In this component, we have a button called Change Name, and when we click on it, it runs the method changeName()
, which emits a custom event changename,
and pass on the updated name John with it.
<template>
<div class="hello">
<button @click="changeName()">Change Name</button>
</div>
</template>
<script>
export default {
name: "Child",
methods: {
changeName() {
this.$emit("changename", "John");
},
},
};
</script>
App.vue (Parent Component)
In the parent component, we listen to the event named @changename
and when it gets changed in the child component, it updates the myName data variable and displays it on the template.
<template>
<div id="app">
My Name is {{ myName }}
<Child @changename="myName = $event" />
</div>
</template>
<script>
import Child from "./components/Child";
export default {
name: "App",
data() {
return {
myName: "Alex",
};
},
components: {
Child,
},
};
</script>
That’s it, now you can update data from the child to the parent component.
CODE HERE:
Related Topics:
How to listen for props changes in VueJS?