Vue.js: EventBus.$on is not properly transmitting the received value

I recently started working with Vue and am currently exploring the best way to organize my event bus. In my project, I have a main layout view (Main.vue) that includes a router view where I pass emitted information from a child component like this:

<template>
<layout>
<router-view :updatedlist="mainupdate" />
</layout>
</template>
import { EventBus } from './event-bus.js'
export default {
  data () {
    return {
      mainupdate: []
    }
  },
mounted () {
    EventBus.$on('listupdated', item => {
      this.mainupdate = item
      console.log(item)
    })
  }
}

The structure of my project is as follows: Main.vue contains Hello.vue, which makes an axios call to fetch data that it then passes on to child components such as Barchart.vue, Piechart.vue, and Datatable.vue.

In Hello.vue, the axios call populates a data property called list. I check if the prop updatedlist (sent from Datatable.vue to Main.vue when something changes) is empty, and if so, set it to the value of list.

Although I can see that the event is successfully emitted and received by Main.vue based on the data displayed in the console, my child components are not updating even though they use updatedlist as their data source. (They do update upon page reload, but why aren't they reactive?)

UPDATE: To try and address the issue, I removed the top-level parent Main.vue and placed the EventBus$on inside Hello.vue instead. However, this resulted in two problems:

  1. Upon each page refresh, the console log adds one more entry to the list, displaying all previous logs as well. This means the list keeps growing until the app is restarted.
  2. My child components STILL do not get updated :(

UPDATE 2: It seems that the lack of reactivity in my chartsjs components, specifically in Barchart.vue and Piechart.vue, is causing the issue with the updates. A basic component I created to simply display the total length does get updated correctly. However, the mystery of the excessive duplicate console logs remains unsolved. Any suggestions?

Answer №1

It seems like you might have a solution to the initial question? In response to your recent update, it appears that you may be experiencing duplicate logs due to not removing event handlers properly. When you attach an event handler to a bus, such as:

mounted () {
    EventBus.$on('listupdated', item => {
      this.mainupdate = item
      console.log(item)
    })
  }
}

It is crucial that you take responsibility for removing it yourself. Otherwise, you end up adding a new handler every time the component is mounted.

I recommend moving the actual handler into a method:

methods: {
  onListUpdated(item){
     this.mainupdate = item
     console.log(item)
  }
}

Transfer the code to add the handler to the created lifecycle hook:

created() {
    EventBus.$on('listupdated', this.onListUpdate)
  }
}

Additionally, include a beforeDestroy handler:

beforeDestroy(){
   EventBus.$off("listupdated", this.onListUpdate)
}

Remember to implement these steps in every component where you are attaching event handlers to EventBus.

Answer №2

It's unclear whether you need to adhere to the current structure or not. Personally, the following method works perfectly for me.

// wherever you initialize your vue.js
// e.g.
window.Vue = require('vue');

// create a central event bus
Vue.prototype.$bus = new Vue();

Now, you can easily access the event bus in any component by using

this.$bus.$on( ... )

Although I may not have knowledge of your complete event bus code, this approach should work effectively.

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 benefits of using Lifery Ajax URLs?

I'm currently using the Grails portlets plugin and I'm exploring how to properly route AJAX methods. It seems like <portlet:actionURL> is only able to map to methods that return models for GSPs, while <portlet:resourceURL> doesn&apos ...

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view ...

Guide on combining item costs and showing the total price using Vuejs and Vuex

I need help with writing code in vuex to pull data as a getter from Cart View. Specifically, I want to display the total price of chosen products and ensure that it is added up and displayed correctly. Any guidance on how to achieve this would be appreciat ...

When using a custom AJAX function, make sure that bindings are functioning properly when setting properties within a callback in Ember

I've encountered some unexpected behavior while trying to set an Ember property inside a custom AJAX function callback. The AJAX function is triggered in the route, as seen in the code snippet below. The success callback updates the 'session.aja ...

"Exploring the process of comparing dates using HTML, AngularJS, and Ionic

I am working on an HTML file that shows a list of notification messages. I am trying to figure out how to display the time difference between each notification. The code snippet below displays the notifications and includes the time for each one: <ion- ...

Moving information from a Vue.js component to a different container

Can I transfer some data? In my Vue component (child), I have: {{ checked.length }} This is responsible for the number of selected items. However, I need to display that information in another div (parent Vue) that is not within the view component. Upd ...

Updating a nested object within an array in a ReactJs component

I am struggling with updating a nested object within an array in the state of my React application. My goal is to determine if an item already exists in the state based on its name. Here's what I'm aiming for: Add an item to the cart. If th ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

What is the best way to retrieve the ajax response using Ajax.Responders in prototype.js?

I am looking to retrieve the response of each Ajax call within the function below Ajax.Responders.register({ onCreate: function() { }, onComplete: function(transport) { }, onSuccess: function(transport) { }, }); ...

The elusive cookie in NodeJS remained just out of reach

After setting a cookie using the code below: router.get("/addCartToCookie", function(req, res) { let options = { maxAge: 1000 * 60 * 15, httpOnly: true, }; let cartData = { name: "test cookie", slug: slugify(&quo ...

What is the best way to find the vertex positions of a JSON model in

Here is the code I am using to load a 3D model in THREE.js: var noisenormalmap = THREE.ImageUtils.loadTexture( "obj/jgd/noisenormalmap.png" ); noisenormalmap.wrapS = THREE.RepeatWrapping; noisenormalmap.wrapT = THREE.RepeatWrapping; noisenormalmap.repeat. ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Error in Vuepress: Attempting to read properties that are not defined (specifically 'match')

I encountered an error while attempting to build my vuepress project. I followed this npm quickstart guide: After adding some pages, everything was functioning correctly with: npm run:dev However, when I tried to generate html to docs/src/.vuepress using ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

Common causes leading to my header component experiencing hydration errors in Next.js

I am currently developing a job portal and encountering an issue with user authentication using JWT in combination with local storage. The problem arises in my header component when the user is authenticated, and if the web page is reloaded, I receive a hy ...

Creating a responsive layout that sets the window height to 100% and automatically adjusts sibling divs when the content within parent divs exceeds the defined height

<section> <div class="section-wrap"> <h1>page1</h1> </div> </section> <section> <div class="section-wrap"> <h1>page2</h1> </div> </section> My attempt at impleme ...