Vue.js view fails to refresh upon receiving an event through eventbus

Just diving into Vue.js 2 and working on my very first (vue) web application. The setup includes two components - a header component and a login component. Once the login process is successful, a "loggedIn" flag gets toggled within an authentication service. This service then triggers an event to inform the header component (and potentially other listening components) that the user has logged in. Consequently, the header should update its display to show the username.

So far, all seems well with events being generated and transmitted using a global event bus. However, upon receiving the event in the header component, it fails to reflect the changes in the view.

I've experimented with various techniques such as basic subscriber patterns, Vuex, and now the event bus, but none seem to resolve the issue. Any insights into what might be causing this problem?

EventBus.js:

import Vue from 'vue'
var eventBus = new Vue()
export default eventBus

SessionService.js

import eventBus from '../util/EventBus'

class SessionService {
  loggedIn=false
  constructor () {
    if (this.isValid(this.getSessionToken())) {
      this.loggedIn = true
    }
  }
  setSessionToken (token) {
    localStorage.setItem('token', token)
    if (this.isValid(token)) {
      eventBus.$emit('LOGGEDIN')
    } else {
      eventBus.$emit('LOGGEDOUT')
    }
  }
  getSessionToken () {
    return localStorage.getItem('token')
  }
  isValid (token) {
    return token !== undefined && token != null && token !== ''
  }
}
var sessionService = new SessionService()
export default sessionService

Header.vue: Script

import eventBus from '../../services/util/EventBus'
var loggedIn = false
var m = this
eventBus.$on('LOGGEDIN', function () {
  console.log('RECEIVED')
  m.loggedIn = true
})

export default{
  name: 'Header',
  data () {
    return {loggedIn}
  }
}

Header.vue: HTML

<template>
  <div>
  <nav class="navbar navbar-expand-lg ap-top-nav">
    <div class="container" >
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">

        <form class="form-inline my-2 my-lg-0 mr-auto">
          <div class="ap-searcher">
            <input class="ap-search" type="text" placeholder="Search" aria-label="Search"/>
            <i class="fa fa-search"></i>
          </div>

        </form>
        <div class="logo ml-auto mr-auto">
          <img src="../../assets/images/logo.png"/>
        </div>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item ap-button blue wide">
            <router-link to="/login">Login: {{loggedIn}}</router-link>
          </li>
          <li class="nav-item ap-button light-blue wide">
            <router-link to="/registration">Register</router-link>
          </li>
          <li class="nav-item ap-button blue-border">
            <a href="#">EN <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
          </li>
        </ul>
      </div>

    </div>
  </nav>
    <nav class="navbar navbar-expand-lg ag-bottom-nav">
      <div class="container">
        <div class="collapse navbar-collapse " id="navbarNav">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <router-link class="nav-link ap-link" to="/">Auctions</router-link>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Lots</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Organize your own auction</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Contact </a>
            </li>
          </ul>
        </div>
      </div>

    </nav>
    <div class="ap-line">
    </div>
  </div>
</template>

Answer №1

When setting up the 'LOGGEDIN' listener in your Header.vue component, ensure that you are accessing the Vue instance correctly within the scope of the component.

To achieve this, it's recommended to place the logic inside the created hook of the component. This way, the eventBus listener will still be registered during component instantiation while allowing this to reference the Vue instance:

import eventBus from '../../services/util/EventBus'

export default {
  name: 'Header',
  data() {
    return { loggedIn: false }
  },
  created() {
    let self = this;
    eventBus.$on('LOGGEDIN', function () {
      console.log('RECEIVED')
      self.loggedIn = true
    })
  }
}

Answer №2

Your Header component code seems a little unusual, however, I believe it should be structured as follows:

  export default {
    name: 'Header',
    data() {
      return { loggedIn: loggedIn }
    }
  }

Answer №3

Outdated, However the solution is '=>' ARROW_Function

  eventBus.$on('LOGGEDIN', (data)=>{
  console.log('RECEIVED')
  self.loggedIn = true
})

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

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

What is the best way to hide the background of an extension's HTML?

Currently, I am working on developing a Chrome extension for a university project. However, I am facing challenges in making the background or body of the extension's HTML completely transparent to achieve a cleaner interface. The issue specifically l ...

Centering a button within a table-cell through movement

I'm facing an issue with aligning a button placed inside a table cell. The table setup is as follows: <b-table v-if="rows.length" :thead-tr-class="'bug-report-thead'" :tbody-tr-class="'bug-report-tbody& ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Jquery allows for the toggling of multiple checkboxes

I have a group of check-boxes that I would like to toggle their content when checked. Currently, I am using jQuery to achieve this functionality, but I am searching for a way to optimize my code so that I do not need to write a separate function for each ...

Encountering an error when attempting to include React TypeScript onChange with a Material UI switch component

I'm working on implementing a show/hide functionality using a switch. I want the component to be displayed when the switch is turned on and hidden when it's turned off. Here's the code I've written: const VirtualEventSection = ({ con ...

difficulty encountered when attempting to input multiple values into a single text field

There are four boxes containing values. When clicking on a box, the value should appear in a text field separated by commas if multiple boxes are selected. <li><a href="javascript:void(0)" onclick="check_stalls('A-14')" id="A-14">A-1 ...

Detect the element that initiated the AJAX call in Jquery event handling

My goal is to capture the beforeSend event for all form submits on my site without interfering with jquery.unobtrusive-ajax.js. I've attempted the following method: $(document).on("ajaxSend", function (e, request, settings) { console.log ...

The EJS is throwing an error because it cannot define the property "round" on an undefined object

I'm currently delving into the realm of Node.js, using the "Secrets of Ninja" book as my guide. I've come across an EJS program in the book that I copied verbatim to run, but I encountered an error despite not making any modifications to the code ...

Using Javascript to save basic high scores to a server

My JS game involves updating a score variable. When the game reaches a gameOver state, I want to compare the score to one saved on the server. If the player got a higher score, I'd like to overwrite the previous high score with the new one. If it&apos ...

Despite successfully connecting to my webservice, the ajax function encounters an error

<script type='text/javascript'> $(document).ready(function () { $("#submit").click(function (e) { e.preventDefault(); var userName = $("#username").val(); var pwd = $("#password").val(); authenticate(use ...

What are some ways to stop the form from refreshing while still successfully submitting the form data on the current

As my form continued to submit and refresh, I consulted a helpful resource on Stack Overflow titled How to prevent page from reloading after form submit - JQuery in search of a solution. Interestingly, the difference between the provided answer and my situ ...

Extract the JSON information to find the <highlighting> tag used to emphasize text within a specific field

{ "responseHeader": { "status": 0, "QTime": 32 }, "response": { "numFound": 21, "start": 0, "docs": [ { "description": "A unique wave design sets apart this wedding band, craft ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

Node.js client encounters ENOBUFS error due to excessive number of HTTP requests

Currently, I have the following setup: An end-to-end requests system where a node.js client communicates with a node.js server. However, the issue arises when the client fails with an ENOBUFS error in less than a minute. client: (function(){ var lo ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: https://i.sstatic.net/iy0ZV.png https://i.sstatic.net/trfrL.png Here is my ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

How can you retrieve the component's state from a higher level without relying on useContext?

I have a question regarding creating expanding flex cards. I found an example on Codepen that showcases what I'd like to achieve: https://codepen.io/z-/pen/OBPJKK In my code, I have a component called HomeButtons that generates these flex cards. With ...

Can I use leaflet to customize the types of roads displayed on the map?

Is there a way to customize the types of roads displayed at different zoom levels using data from the OSM highways list? I have checked the Leaflet documentation but couldn't find the answer. If you happen to come across it, please share the link. e ...