Home » vue » Vue.js $emit event from parent and receive it on a component (child)

Vue.js $emit event from parent and receive it on a component (child)

Posted by: admin November 26, 2021 Leave a comment

Questions:

I can’t seem to get this working!

I have added the $emit code to my click event to emit a custom event.

<h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)">Add New</a></h2>

I then listen for this event on my component within the same Vue application, I do this on the template, I would much rather do this within the code:

<business-hours :injected-data="hours" :injected-days="data.days[0]" v-on:addBusinessHours="test()">

Not sure if this will affect it, but my business-hours component is within another component.

Answers:

I’d recommend you using a separate class in order to emit events from components.

First create your Event class, as an example, I’m calling EventBus.

/* Events.js */
import Vue from 'vue';
export const EventBus = new Vue();

Then you import to the component you wish to emit the values from:

import {EventBus} from '@/events.js'

Then you dispatch the event

<h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="emitEvent('addBusinessHours', null)">Add New</a></h2>


emitEvent(name, params) { EventBus.$emit( name , params ); }

On your business-hours component you import the EventBus and add an event listener to listen to the dispatched event

created() { 
   EventBus.$on('addBusinessHours' , () => console.log('Business hours component received event from other component' );
}

That should give you a way forward towards sending and receiving events with Vue.
You can also check this tutorial for reference for a better understanding of how Events works.

https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

Good luck