Vue.js global event issue

Recently, I encountered an issue with the following code:

<component-one></component-one>
<component-two></component-two>
<component-three></component-three>

Specifically, component-two contains component-three.

My current setup involves emitting an event in <component-one> that needs to be caught in <component-three>.

In <component-one>, I emit the event like this:

this.$bus.$emit('setSecondBanner', finalBanner);

Then, in <component-three>, I attempt to catch it:

mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},

However, the event is not being caught as expected.

The event bus is defined in my core.js file as follows:

let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});

Upon inspecting vue-dev-tools, I confirm that the event has indeed been fired. So, what could be causing the issue?

Answer №1

This is a demonstration of how Vue1 works.

Object.defineProperty(Vue.prototype, '$bus', {
get() {
return this.$root.bus;
}
});

Vue.component('third', {
template: `<div> Third : {{ data }} </div>`,
  props:['data']
});

Vue.component('second', {
template: `<div>Second component <third :data="data"></third></div>`,
ready() {
this.$bus.$on('setSecondBanner', (event) => {
this.data = event.data;
});
},
data() {
return {
    data: 'Default value in second'
    }
}
});

Vue.component('first', {
template: `<div>{{ data }}</div>`,
ready() {
setInterval(() => {
this.$bus.$emit('setSecondBanner', {
data: 'Bus sending some data : '+new Date(),
});
}, 1000);
},

data() {
return {
    data: 'Default value in first'
    }
}
});

var bus = new Vue({});
new Vue({
el: '#app',
data: {
bus: bus
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
  <second></second>
  <first></first>
</div>

Answer №2

Did you attempt to initialize the listener in the created hook instead of the mounted hook?

Additionally, what's the reason for creating the bus with defineProperties rather than just using:

Vue.prototype.$bus = new Vue();

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 are the steps for adding a JSON file to a GitHub repository?

Could someone lend a hand with my GitHub issue? I recently uploaded my website to a GitHub repository. The problem I'm facing is that I have a JSON file containing translations that are being processed in JavaScript locally, and everything works fine ...

Angular ng-repeat not populating the list properly, causing a collapse not to display

Currently, I am working on developing an app using Angular.js and Bootstrap UI, but I have run into a problem with a collapse navigation feature. The issue I am facing is that I have an ng-repeat that should be functioning properly. However, when I click ...

The Dockerfile for Next13 is unable to locate the server.js file

When using the official Dockerfile from Next with the examples provided, I encounter an error while trying to build the app using a Dockerfile and docker-compose. b78-client-1 | node:internal/modules/cjs/loader:1078 b78-client-1 | throw err; b78-client ...

Is there a way to transfer the chosen maximum and minimum price values to a JavaScript function within a select tag in HTML?

I have a search form that includes select options with two values. However, I want to have two select options for both the Max and Min price values. <input type="hidden" id="budget_min" name="filter_budget_min" value="0" /> <select onchange="upda ...

Creating an error handler in PHP for dynamically adding or removing input fields is a crucial step in ensuring smooth and

I designed a form with multiple fields, including a basic input text field and dynamic add/remove input fields. I successfully set the first field as required using PHP arguments, but I'm struggling to do the same for the additional fields. I need as ...

How to Retrieve the Value from Bulma Datepicker in Vue.js

Currently, I am facing an issue with the bulma vuejs datepicker where I am unable to fetch the value as it keeps returning null. Here is the link to the datepicker that I am using. Here is a snippet of my <date-picker> component: <template> ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

What could be causing my select tags to appear incorrectly in Firefox and IE?

With the help of Jquery, my goal is to dynamically populate a select field when it is in focus, even if it already has a value. Once populated, I want to retain the previous value if it exists as an option in the newly populated field. Although this works ...

What is the best way to perform an AJAX request on Hackerrank using JavaScript?

As I dove into the Hackerrank example test, I experimented with various methods for making an AJAX call. XMLHttpReq, fetch, and others were attempted but none seemed to work; both XHR and fetch methods were unavailable. My first attempt was with fetch: as ...

Upon importing Chakra-UI in NextJS, the functionality may not work right away

Currently, I am diving into learning NextJS and Chakra-UI. Following the installation of Chakra-UI and attempting to import it, I encountered the error message shown below on the page. Any assistance in resolving this issue would be greatly appreciated. ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

Updating the authentication code in passport.js

In the project, there is a passport.js file that contains authentication related code: const axios = require('axios') const uuid = require('uuid/v4') const passport = require('passport') const LocalStrategy = require('pa ...

Decrease the height of a div element from the top with the use of jQuery

My goal is to manipulate the height of the div #target when a specific event is triggered, either by reducing/increasing its height from the top or by hiding/showing its content. However, I'm struggling to find a solution to achieve this. The current ...

Creating one div to initiate the contents to fadeToggle and another div to cease the fadeToggle animation utilizing the setInterval function in JavaScript

Here is the link to my Fiddle: http://jsfiddle.net/tmanundercover/62ap2/ CSS #targetedDiv, #otherDiv { border: 1px solid; } HTML <div id="targetedDiv">&nbsp<span id="fakeCursor">|</span></div> <br> <div id="othe ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Having trouble fetching JSON data from a URL in my React Native project, the response is not as expected

getData() { return fetch("http://bitcfeedcms.rf.gd/script.php") .then(response => { console.log(response); response.json(); }) .then(responseJson => { this.setState({ data: responseJson }); }) .catch(error => { console.er ...

Starting a line series from the beginning of the y-axis on a bar chart using chart.js

We have a new request from the business regarding the implementation of chart.js. Take a look at the image below, which shows a combination of bar and line charts. The line chart contains only a few data points. https://i.sstatic.net/mCSlR.png Within th ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

The order of key:value pairs in documents created by Mongoose does not always align with the schema

Having trouble understanding how the Mongo .create and .findAndUpdate operations work. My mongoose version is 5.4.2X and I have a model with a schema containing multiple key:value pairs in a specific order (using 1. 2. 3. etc to indicate the correct order) ...