Emitting events to multiple components in VueJS with different parent components

I have multiple Vue Components set up like this:

App.js
 |
 |-- CreateTasks
 |
 |-- LatestTasks (displays 20 tasks)
 |
 |-- FooBar
 |   |---LatestTasks (displays 10 tasks)

My goal is to trigger an event from the CreateTasks component when a new task is created, and have all instances of the LatestTasks component update their task list accordingly.

Despite my efforts, I'm having trouble getting this functionality to work properly.

Below is how I've implemented it:

In CreateTasks Component

  methods: {
    createTask(){
      let task = { name: 'newTask' };
      this.$emit( 'new-task-created' );
    }
  }

In LatestTasks Component

  methods: {
    getLatestTasks(){
      // logic to fetch latest tasks
    }
  }
  created() {
    window.addEventListener('new-task-created', this.getLatestTasks );
  },

Answer №1

If you're looking for a more structured approach, consider using Vuex or Redux. However, if you're working on a small project and just need a quick solution using events:

Start by attaching events to the root element:

this.$root.$on('myevent',function(data){console.log(data)})

Then, emit the events from the root element:

this.$root.$emit('myevent',{data:1234}}

Another option is to create an EventBus:

// eventbus.js
import Vue from 'vue'
const EventBus = new Vue()
export default EventBus

Subscribe to the EventBus in your component:

// component1.js
import Vue from 'vue'
import EventBus from './eventbus'
Vue.component('component1', {
  mounted () {
    EventBus.$on('myevent', function (data) {
       console.log(data)
    });
  }
});

Emit an event through the EventBus:

// component2.js
import Vue from 'vue'
import EventBus from './eventbus'
Vue.component('component2', {
  methods: {
    emitMethod () {
       EventBus.$emit('myevent', {data: 1234});
    }
  }
});

Answer №2

If you're looking for the best way to manage state in your Vue application, consider using Vuex. Instead of emitting events within a method like createTask(), you can utilize the dispatch() method to trigger an action in the Vuex store. Then, in any component that needs access to this data, simply create a computed property that connects to the appropriate Vuex getter.

For more information on how to use Vuex, check out the Vuex Docs.

Alternatively, you could still emit an event as originally suggested, but you would need to listen for it in the parent component, store it in a local variable, and then pass it down to child components through props. This approach may require more setup, but can be effective depending on your specific needs.

I hope this explanation helps. If you'd like, I can provide a more detailed example to assist with implementing these concepts in your project.

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

Achieving dynamic key assignment when updating with mongoose in NodeJS and Express

With a multitude of keys requiring updates from a single function, I am seeking guidance on how to dynamically set the key for updating. static async updateProfile(req, res, next) { const userId = req.body.userId; // The key requiring an update ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

What is the reason for initializing I with the length of the response?

I am attempting to generate a table using an AJAX JSON response, but the for loop sets i to the maximum value right away. $.ajax(settings).done(function (response) { console.log(response); var i = ""; td = document.createElement('td'); t ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

"Utilizing Node.js and Express to return JSONP data based on

For some reason, my Express application is giving me a strange result when using res.jsonp. It looks like this: /**/ typeof jsonp1406719695757 === 'function' && jsonp1406719695757({"published":true,"can_add_to_cart":true,"updated_at":"20 ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Guide to configuring the API key within the Stampery API.JS script

Currently, I'm in the process of configuring Stampery but I'm facing difficulty locating where to insert the string API key within the API.JS file. The documentation mentions setting the STAMPERY_TOKEN as the API key, but I'm unsure how to p ...

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

What occurs if the user navigates away from the page before the AJAX call has finished?

In my app, I use an asynchronous AJAX call for each page that loads in order to track a user's flow through the application. Usually, the server request to record the visit happens quickly. However, there are instances where I seem to be missing some ...

Verify the presence of an email in the database utilizing a custom express-validator for node, express, and mysql

//Endpoint to update the user's email address. apiRouter.post('/update-email', [ check('newEmail') .isEmail().withMessage('Please enter a valid email address') .custom(newEmail=> { db.query(`SELECT user ...

Having trouble with incorporating multiple sliders on your website using W3.CSS?

I'm in the process of designing a portfolio website and have decided to incorporate modals to showcase my projects. I've opted to use the W3.CSS framework for this purpose. The issue I'm currently facing is that only the first slideshow see ...

Unraveling JSON Data from a PHP Website with Jquery

I need to retrieve data from a database and store it in an array, similar to the example below var locations = [ ['Current', 18.53515053, 73.87944794, 2], ['VimanNagar', 18.5670762, 73.9084194, 1] ]; To begin with, I have created a ...

Obtaining the category value within a slot of the Vuetify calendar

I am struggling to implement hover functionality in the categories view of Vuetify calendar within the body section (slot day-body). When I try to add hover functionality, the entire row ends up being affected by the hover effect, even though I only want i ...

Cities cannot be obscured by a rotating globe

In my latest project, I have created a jsfiddle showcasing a Bostock spinning globe implementation. After successfully plotting a few city markers, I encountered a problem where not all cities were being displayed. Additionally, the script intended to hid ...

Is there a way to retrieve the original value of the substr value?

I successfully retrieved the correct value using the substr() method, but I am facing difficulty in getting back the original value. Can someone please guide me on how to achieve this? For example: "AAAAAA" -> AA... but I am unable to revert from AA.. ...

Manipulate the dimensions of an item in Three.js

I am a beginner in Three.js and I am looking to create a 3D scene with multiple objects floating in the sky and a scale displayed on the screen. The scale should be movable up and down to bring the objects closer or further away, creating the illusion of ...

An endless cycle occurs in the watcher when trying to refresh data from Vuex

I am facing an issue with a "dumb" component that receives props from a parent. The user has the ability to change a selector which triggers an action (using Vuex) to fetch new data. Once the new data is received, I need to pass it to the child component a ...

LoadJSON data in P5 JavaScript is delayed

When attempting to read a Json file using loadJSON from p5, I am encountering a delay in receiving the data. When I use console.log(JSON.stringify(data)), it displays {}. function setup() { for(i = 0; i <= 3; i++) { //Loading the ...

Issues with Vue.js interceptors preventing them from properly working and failing to return any

I have encountered an issue with axios interceptors. I attempted to set a header for jwt using interceptors, but nothing seems to be working as expected. To debug this problem, I modified my code and added a simple console.log statement. However, when I ...

Utilizing functions for object creation in JavaScript

Having trouble with creating a function that automatically generates an object and then alerts its properties. Can't seem to get the alerts when I click the button. Any assistance would be appreciated. <html> <head> <s ...