Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from the listener. Despite trying various solutions over the past 3 days, nothing seems to work. Any help would be greatly appreciated.

Initially, I attempted to create an eventBus in app.js but that did not resolve the problem either.

Here is a snippet of my EditDiscountComponent:

import { EventBus } from "../../../event-bus";

editDiscount () {
        const data = {
          discount_id: this.discountData.discount_id,
          status: this.discountData.status,
          type: this.discountData.type,
          percentage:this.discountData.percentage,
          amount:this.discountData.amount,
        };

        EventBus.$emit('update-discount', data);

         this.languages.forEach(lang => {
              if (lang.code && this.discountData[lang.code] !== undefined) {
                  data[lang.code] = this.discountData[lang.code];
              }
          });
        this.$store.dispatch(actions.EDIT_DISCOUNT, data)
          .then(res => {
            if (res && res.data.status) {

              // window.location.href = '/admin/discounts';

            } else {
              this.$store.commit(mutations.SET_SNACKBAR_SHOW, true);
              this.$store.commit(mutations.SET_SNACKBAR_TEXT, res.data.message);
            }
          }).catch(console.error);

      },
    },

And here is a snippet from my ProductComponent:


import { EventBus } from "../../../event-bus";

 mounted() {
            EventBus.$on('update-discount', ($data) => {
                console.log($data);
            });
            this.getCategories();
            this.getProducts();
        },

Despite attempting different ways to use the callback function, the desired results were not achieved. The event listener was also tried within the mounted() hook without success.

Answer №1

To start implementing global event handling in your Vue project, you can create a file named eventBus.js within the src folder.

import Vue from 'vue'
export default new Vue()

Once you have created the file, you can import it into your components using the following syntax:

import EventBus from '@/eventBus'

If you need more guidance on this topic, you can check out this helpful resource: https://alligator.io/vuejs/global-event-bus/

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

When was Chrome first updated to include timezone offset support for Intl.DateTimeFormat()?

My experience with Chromium 121 has been positive using the Intl.DateTimeFormat as shown below: new Intl.DateTimeFormat('en', { dateStyle: 'long', timeStyle: 'long', timeZone: '+0500', }).format ...

Loading a series of images in advance using jQuery

I have a series of frames in an animation, with file names like: frame-1.jpg, frame-2.jpg, and I have a total of 400 images. My goal is to preload all 400 images before the animation begins. Usually, when preloading images, I use the following method: v ...

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

How to show or hide a textbox in JavaScript?

Within my user control, there is a panel with two controls: ddlType, a drop-down list, and txtOthers, a text box. Initially, txtOthers is set to be invisible. The goal is for txtOthers to become visible when the user selects an option in ddlType that corr ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Is there a method to use media queries to dynamically switch JavaScript files based on the user's device?

I've been working on optimizing the mobile layout of my website, and while I have successfully implemented a media query with a different stylesheet for mobile devices, I'm struggling to determine if it's feasible to also load a separate Jav ...

Problem encountered with @HostListener

In an Angular component, I have the following code snippet that is functioning as intended: @HostListener('document:click', ['$event']) onClick(event) { if(!this.eRef.nativeElement.contains(event.target)) { console.log("clicked out ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

difficulty in making an https request

My application was developed using OFFICEjs and was functioning properly on LOCALHOST. However, last week it suddenly started throwing an error message - "XHR Error." This issue arose out of nowhere, as I hadn't made any changes to the code over the w ...

Is it possible to integrate Processing JS on top of an HTML element?

I have currently integrated Processing JS with the HTML canvas element on a website. The goal is to have the Processing JS animation run smoothly over the existing HTML elements on the page. You can check out the site at [usandthings.com][1] to get an idea ...

Retrieve information from the NodeJs server pertaining to the previous 10-minute timeframe

While working on a project where I needed to fetch and display data from a website within the past 10 minutes that meets a certain condition, I initially thought of storing it in a global variable. However, I realize that this may not be the best practice. ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Incorporate h:outputText into your JavaScript code segment

After populating some information into a h:outputText, I am now looking to trigger a JavaScript function upon clicking a button that will retrieve the text from the outputText. The structure of the code is as follows: <p:tabView id="tabView"> & ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Reasons why the Express Route fails to store cache while executed in a separate file

My code works fine when it's all in one file, but the caching stops working when I move it to a separate middleware file. Can someone help me understand why the caching isn't functioning properly in my middleware? Here is the working code: var e ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...