Update Parent data from child component in VueJs

featured Image

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:

update parent from child vue

Edit g48ix

Related Topics:

How to listen for props changes in VueJS?

How to call a function in VUE template?

Call a Vue.js Component Method From Outside The Component

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *