The event emitted doesn't appear to be caught by EventBus.$on in Vue.js

Currently trying to trigger an event from router.beforeEach and listening for it in another component. Although the vue devtool confirms that the event is being triggered, my component seems unable to capture it. Thank you for your help.

This is how I declared my EventBus:

import Vue from 'vue'
export const EventBus = new Vue()

This is how I'm triggering the event:

router.beforeEach((to, from, next) => {
            console.log('from', from.name, 'to', to.name)
            window.axios.get(checkTokenUrl, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('JWT')}`
                }
            }).then(res => res.data)
                .then(data => {
                    next()
                    if (data === true) {
                        console.log('User is Logged in')
                        EventBus.$emit('Logged-in')
                    } else {
                        console.log('User is Logged out')
                        EventBus.$emit('Logged-Out')
                    }
                })
        
        })

This is how I'm catching the event:

EventBus.$on('Logged-Out', () => {
                this.isUserLoggedIn = false
                localStorage.setItem('JWT', '')
            })

            EventBus.$on('Logged-in', () => {
                this.isUserLoggedIn = true
            })

Answer №1

An issue arose when I accidentally reversed the order in which the listener and emitter were being initialized. This resulted in the listener being created after the emitter, leading to the problem at hand.

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

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

What is the best way to save an integer in HTML's localStorage instead of a string?

I've encountered an issue while using the localStorage feature in a game I'm developing. Specifically, the money variable should be increasing by 1 every second. Here's a snippet of my code: var money = 0; window.onload = function () { ...

Discover the secret to restricting JSON API functionality in your WordPress plugin

I am interested in using WordPress to build a website, specifically looking to export site posts using the JSON API. However, I encountered an issue when attempting to limit the displayed posts by category. Clicking on the "get_category_posts" link within ...

Picking a variety of elements and determining their heights using the height

I'm curious why this jQuery code isn't working as expected: hdr = $('.header-wrapper, #top-bar, #new-showroom-header').height(); My intention is to retrieve the heights of multiple elements and store them in a variable. I assumed that ...

How can you enhance your HTML elements by incorporating classes and other features?

At this moment, the code I have is: var carDiv = $("<div/>").appendTo("#content"); var eUl = $("<ul/>").appendTo(carDiv); How can I transform it into <ul data-role="listview"> content </ul> Instead of <ul> ...

Extract the complete HTML information from the weather website

Currently, I am attempting to retrieve weather data from the following website: using this code snippet: try { int i = 0; if (googlefirst3.startsWith("http")) { Document document = Jsoup.connect("https ...

Verification of Phone Numbers (Global)

I am attempting to create a validation check for mobile numbers, similar to the one implemented by Gmail. Check out Gmail's signup page here However, there is significant variation in phone number formats across different countries, making it challe ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Transferring information between pages through ajax communication

I am working with two pages named testing.php and submission.php. My goal is to send data from testing.php to be displayed on submission.php. For example, when a user clicks on test1, they should be directed to submission.php where I want to display the te ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

What is the best way to adjust the size of table columns dynamically to accommodate content, align them to the left, and set a maximum

I came across many examples that are somewhat close to what I need, but I require more control over the table design. I want to prevent text wrapping, display ellipsis, and provide a tooltip when hovering over the content to view it completely. This proje ...

Surprising symbol encountered: JavaScript, Node.js, and MongoDB

                 I am facing an unexpected identifier error while running the code below when trying to check if the documents' state has changed. Despite exhausting my Google search and looking for documentation on MongoDB, I am yet to find ...

Leverage props in Vue.js in combination with Symfony

I am struggling to retrieve a variable passed in the URL from Twig and send it to VueJS for calling an API. However, I am facing issues with using PROPS from VueJS. Below is my Twig template: {% block body %} <Realmstatus v-bind:region="{{ app.req ...

Enhancing user experience: Implementing specific actions when reconnecting with Socket.io after a disconnection

I am working on a game using node.js and socket.io. The code I have written is quite simple. The game starts animating as soon as it connects to the server and continues to do so. My main concern is ensuring that the game handles network and server disco ...

When I resize the screen size, my multiple item carousel in Bootstrap is failing to adjust and collapses

Whenever I try to resize the output screen, the carousel collapses and the last few items disappear. I really need the carousel to stay intact even when resizing. Can someone please assist me with this issue? Link to my CodePen ResCarouselSize(); $(w ...

Storing combined data as an object within a single field in Laravel's store functionality

Currently, I am facing a challenge in storing repeater data into the database using Laravel. To achieve this, I need to merge some data with varying values. The structure of my form is as follows: <div v-for="(tab, tabIndex) in tabs" :key=&qu ...

An error occurred as the requested resource does not have the necessary 'Access-Control-Allow-Origin' header. The response code received was 403

I am working with Angular products services that make calls to the "http://jsonplaceholder.typicode.com/posts" URL using the HttpClient method. However, I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on t ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

The difference between using document.getElementsByTagName("img") and document.getElementById('testimg')

My HTML code is as follows: <a href="index.php"><img id="testimg" src="images/logo.png"/></a> This is my JavaScript code: function getW(){ var theImg = document.getElementById('testimg'); return theImg; } theImg = ...