Emitting an event to a Vue.js component from the parent

We are trying to accomplish an event based mechanism for updating a component.

There is a scenario that you are trying to accomplish, and that is to update the child component of the parent view. In our case the HelloWorldCard.vue is our child component and HelloWorld.vue is the parent.

<template>
  <div>
    <helloworld-card></helloworld-card>
    <b-form-input v-model="fullName"type="text" placeHolder="Enter your name"></b-form-input>
    <b-button v-on:click="onEmit()">Emit Event</b-button>
  </div>
</template>

Inside the HelloWorld.vue template we reference the helloworld-card component so that the parent may render it, however, on a button click inside the parent we need to notify the child of the new changes. As you can see there is an onEmit() method being called when you click the button. The code for the onEmit method is as follows.

onEmit() {
  this.$emit('GREET_EVENT', this.fullName);
}

I just named it “GREET_EVENT”, and passing the fullName as an argument to the event handler, which is implemented in the child component HelloWorldCard.vue, but before we can trigger anything on an event we have to first register our “GREET_EVENT”.

created() {
  // Register the event handler.
  this.$parent.$on('GREET_EVENT', this.handleGreetEvent)
}

Next, we implement the handleGreetEvent function, this is what is getting called.

methods: {
  handleGreetEvent(fullName) {
    this.fullName = fullName
  }
}

Finally, this.fullName variable gets assigned and we present it in the template.
You can get the code from the GitHub repository.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.