Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work!

I have included the $emit code in my click event to trigger 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>

Next, I catch this event on the component within the same Vue application. I currently handle this on the template, but would prefer handling it in the code:

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

Just a heads up, my business-hours component is nested within another component.

Answer №1

If you want to efficiently emit events from components, I suggest using a separate class for that purpose.

To start, create an Event class, such as EventBus in this example:

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

Next, import the EventBus into the component where you want to trigger events:

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

You can then dispatch the event like so:

<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); }

In your business-hours component, remember to import EventBus and add an event listener to react to the emitted event:

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

This approach will help you effectively send and receive events with Vue. For further insights, you may refer to this tutorial:

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

Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to set breakpoints in a SCSS file when using Vuetify?

Is there a way to implement media query breakpoints in my Vuetify application using SCSS? For instance, Bootstrap allows me to achieve this in a SCSS file: @include media-breakpoint-up(sm) { .custom-class { display: block; } } How can I do the s ...

Having trouble sending a POST request from my React frontend to the Node.js backend

My node.js portfolio page features a simple contact form that sends emails using the Sendgrid API. The details for the API request are stored in sendgridObj, which is then sent to my server at server.js via a POST request when the contact form is submitted ...

The Node.js server is outputting an HTTP status code of 404

I have recently set up a small server. Interestingly, when I attempt to perform a GET request to my server through a browser, I can see the correct data. However, when I try to make a POST request to my server using code, I receive an HTTP status 404 error ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

Using the 'type' field as a parameter in a Vue2 component object

I need help with passing an object into my component. Here is a snippet of the object's properties: { title: "myTitle", type: "myType" } However, when I define the prop in my component like this, I get a Vue runtime warning st ...

Compilation of SCSS is not possible due to a SASS error - there are no .sass files present

After successfully building an application using VueJS, I encountered a sudden error. Despite rolling back to previous versions, the error persists and I cannot pinpoint what caused it to appear out of nowhere. Invalid CSS after "/* banners */": expected ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Access the vue-router router-link component

I am working with a component that includes the following code: <router-link to="page"></router-link> <router-view></router-view> Within the Page component linked by the router, an event is triggered. The component containing the ...

The implementation of SetInterval within nested functions in JavaScript appears to be malfunctioning

I am a beginner in the world of JavaScript and I am currently attempting to incorporate the setInterval method within functions in Js. JavaScript Code: var tar = document.getElementById("sample"); function dataSample(tar) { //setInterval ...

Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked. Initially, I attempted to mock ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Utilizing Jquery Autocomplete with multiple arrays for data sourcing

I am facing a challenge where I want to display both doctors and their connections in an autocomplete search using jQuery. Although I have successfully displayed the doctors, I'm struggling to categorize and display data from both arrays separately un ...

"Enhanced jQuery confirmation dialog plugin with full screen functionality and automatic

My current web-based production tracking system isn't getting the attention it needs from users, so I'm in the process of creating a full-screen alert and confirm function to ensure they pay closer attention. The idea is for alerts to remain on t ...

Prevent users from deleting options in Autocomplete by disabling the backspace key

I am currently working on implementing the Autocomplete component from Material-Ui library to allow users to select multiple options, but I want to restrict them from directly removing any of those options. One issue I've encountered is that users ca ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

ReactJS encountered an error: [function] is not defined, July 2017

Attempting to convert a JSON file into an array and then randomly selecting 5 items from it. I suspect the issue lies in my render/return statement at the end of ImageContainer.js, but as a newbie in ReactJS, it could be anything. Any assistance or guida ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

"Encountered a Http502 error while running the Node component (code provided for reference purposes

Encountering the Http502 error while developing a node component for chatbot. The first code snippet works flawlessly, but the second one triggers an Http502 error. Both snippets share the same host and proxy settings, with only the endpoint being differen ...

Issue with VueJS beforeRouteEnter hook not triggering

I have been following the steps outlined on this page: https://github.com/vuejs/vue-class-component#adding-custom-hooks Although no errors are appearing, the beforeRouteEnter hook is not triggering. I am not getting any of the expected console output. In ...