Update Parent data from child component in VueJs
This article is about how to update parent data from a child component in vuejs. We will use custom events to pass data from child to parent component.
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?
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
