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

Guide on creating a project for developing an npm package

Within my git root project, I am utilizing a git subproject called UIComponents. For instance, my main project is named MyApp and the subproject is UIComponents. Currently, I have cloned the UIComponents repository inside my project folder and added UIComp ...

Nestjs crashes with "terminated" on an Amazon EC2 instance

https://i.stack.imgur.com/3GSft.jpgMy application abruptly terminates with the error message "killed" without providing any additional information or stack trace. Interestingly, it functions properly when run locally. Any assistance would be greatly appr ...

Filtering out Objection/Knex query results based on withGraphFetched results

I am working with two models in Objection - "brands" and "offers". Brand: const { Model } = require('objection') class Brand extends Model { static get tableName() { return 'brands' } ...

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

Update the styling for the second list item within a specified unordered list class instantaneously

Looking to emphasize the second list item (li) within a selected dropdown list with a designated unordered list class of "chosen-results". <div class="chosen-container chosen-container-single select-or-other-select form-select required chosen-proc ...

Can you explain the functionality of this Angular JS code snippet?

How is it possible that the following code snippet works in Angular JS? var app = angular.module('store',[]); (function(){ app.controller('StoreController',function(){ this.blabla = student; }); })(); var student = ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

What is the best way to execute two asynchronous calls sequentially in JavaScript?

When using a common generic function for AJAX calls, the initial request retrieves all data from the server and maintains it within local scope. However, subsequent requests are still hitting the server, even when the data is already available locally. Thi ...

Using jQuery to duplicate elements by copying and pasting

I am facing a scenario where I need to dynamically create and manipulate a div element in my web application. The process involves appending the newly created div to another container upon clicking a button, followed by triggering a series of functions on ...

Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a b ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Creating an npm package that includes an entire Vue.js application - where to begin?

Can a complete Vue.js application be packaged into an npm package? The documentation I've found only covers packaging individual components, not entire applications. I'm interested in importing a Vue.js app as a web component within another appl ...

JS: I'm struggling to understand the scope

I've been working on adapting CouchDB's JS API to function asynchronously, but I'm encountering an unresolved error: You can find my version of the JS API here on Pastebin. Whenever I execute (new CouchDB("dbname")).allDocs(function(result) ...

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

The issue of nested tabs in Bootstrap 3 causing problems with sliders within the main tab has

Hello, I am utilizing Bootstrap 3 tabs. Within the nav-tabs, there are three tab-panes: the first tab contains text only, the second tab includes a slider, and the third tab has nested tabs. However, I encountered an issue where the slider in the nested t ...

What are the steps to develop a Vue application with a built-in "add to desktop" functionality?

Looking to develop a Vue application with the feature of adding to desktop, similar to the option near the share button on YouTube. Any suggestions on how to achieve this? https://i.stack.imgur.com/nXG4i.png ...