Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below:

EventBus.$on

and

EventBus.$emit('call-modal', { type: 'success' });

Now I'm wondering how I can modify it so that instead of utilizing $on and $emit, I can use this.$root.$emit to make it accessible across all components. I attempted to implement this change, but it's not working currently. Could someone explain why?

Below is the snippet from my App.vue file:

<template >
  <div id="app">
    <bankAccount>
    </bankAccount> 
    <div :class="['modal', `modal--type--${modalType}`]" v-show="showModal">
    <slot name="title">e</slot>
    <slot name="description"></slot>
    </div>
  </div>
</template>

<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue'
export const EventBus = new Vue()

export default {
  name: 'app',
  components: {
    bankAccount,
  },
  data() {
    return {
      showModal: false,
          modalType: 'default',
    }
  },
  created() {
    EventBus.$on('call-modal', obj => {
      this.showModal = true
      this.modalType = obj.type
    })
  },
}
</script>

<style>
.modal {
  height: 100px;
  width: 300px;
  border: solid gray 2px;
}

.modal--type--success {
  border-color: green;
}

.modal--type--danger {
  border-color: red;
  width: 100%;
}

.modal--type--warning {
  border-color: yellow;
  width: 100%;
}
</style>

And here is an excerpt from my component:

<template>
  <div>
   <button class="pleeease-click-me" @click="callModal()">Click me</button>
  </div>
</template>

<script>
import { EventBus } from '../App.vue';


export default {
  name: 'bankAccount',
  data() {
    return {
            showModal: false
    }
  },
   methods: {
    callModal() {
      this.showModal = !this.showModal
     EventBus.$emit('call-modal', { type: 'success' });

    }
  }
}

</script>

<style scoped>

.modal {
  height: 100px;
  width: 300px;

}
</style>

Answer №1

If you want all your components to share the same eventbus instance, consider creating a separate file called eventbus.js and including it in each component. This way, they can all communicate through the eventbus. For more information on this topic, check out:

https://alligator.io/vuejs/global-event-bus/

Here is a detailed explanation:

To start, create an eventbus.js file with the following content:

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

Next, include the eventbus in your components like so:

import { EventBus } from './event-bus.js';

Now you can use the eventbus by listening for events like this:

EventBus.$on("event", function(data){
    // process data
});

Trigger events using the eventbus like this:

EventBus.$emit("event", data);

Remember to clean up by removing the event listener before destroying the component:

beforeDestroy {
     EventBus.$off("event");
}

Answer №2

To implement this functionality, simply include the following code in the instance prototype:

// main.js
//import vue from 'vue'

Vue.prototype.$eventHub = new Vue(); 


// new Vue({
//    ...
//  })

Once added, you will be able to utilize it on any component with the following code:

 this.$eventHub.$emit('call-modal');

Answer №3

To get the results you want, you'll need to make a small adjustment in your code. In your App.vue file, modify these lines of code:

created() {
  this.$root.$on('call-modal', obj => {
    this.showModal = true
    this.modalType = obj.type
  })
},

Next, in your component:

callModal() {
  this.showModal = !this.showModal
  this.$root.$emit('call-modal', { type: 'success' })
}

Note that the suggested approach by @Dadboz is more recommended than what you desire.

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

Steps for choosing an option in MUI select list using jest

I am looking for a way to automate tests for a Material UI select component using Jest. Is there a way to select an option from the list of options in the Material UI component and confirm that its value has been successfully populated in Jest? I have se ...

Issue encountered when integrating vue2-google-maps into a project using vue.js and Laravel 5.6.12

I am currently utilizing Laravel 5.6.12 in combination with vue.js I am attempting to integrate Google Maps using the following GitHub link I am adhering to the instructions provided in the aforementioned link, as follows. Installation npm install vue2 ...

Is it possible to eliminate the use of the `this` keyword in a Vue.js application?

I am currently following the guidelines of Douglas Crockford's jslint, which gives a warning when 'this' is used. The warning displayed is: [jslint] Unexpected 'this'. (unexpected_a) I have not been able to find a solution for th ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

Adding schemas to the router of a Next.js 13 app is a helpful feature that can

Summary: In Next.js 13, the /app router's new changes to layout and page routing have altered how we add content to the <head>. The challenge now is how to include a schema script on each page. Next.js automatically combines <head> tags f ...

Execute multiple events using jQuery's .trigger() method

As I develop a jQuery plugin, I am utilizing the .on and .trigger functions for my pub/sub system. One challenge I am facing is triggering multiple events in different scenarios with ease. My question is whether it is possible to trigger multiple events a ...

Is it possible for a jQuery selector to retain its object? What can be done to prevent it

One interesting scenario involves a dropdown element within a container. <div class='container' /> <script> var dropdown = "<select class='multi-dropdown'> ... </select>" </script> Every time the value ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: this.$root.$emit('new-mess ...

`Apply event bindings for onchange and other actions to multiple elements loaded via ajax within a specific div`

My form includes various input fields, dropdowns, and text areas. Upon loading, jQuery locates each element, sets its data attribute to a default value, attaches an onchange event, and triggers the change event. The issue arises when some dropdowns are d ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

AngularJS initiates an XMLHttpRequest (XHR) request before each routeChange, without being dependent on the controller being used

I'm currently embarking on a new project, and for the initial phase, I want to verify if the user has an active session with the server by sending an XHR HEAD request to /api/me. My objective is to implement the following syntax $rootScope.$on("$rou ...

What is the process for displaying all cookies in node.js?

I recently wrote some node.js code to retrieve cookies for a specific route. router.get('/', function (req, res, next) { var cookies = req.cookies; res.render('cartoons', { Cookies: cookies, }); }); In my cartoons Jade file, the ...

Do the dependencies in the devDependencies section impact the overall size of the

My search for a definitive answer to this question was fruitless. Are the packages I include as devDependencies included in the final production JS bundle, impacting its size? Or does only the dependencies list affect the bundle's content? ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Guide on how to retrieve a response from an API Route and integrate it into the client side of the app router within Next.js

Transitioning from Next.js 12 to 13 has been quite perplexing, especially when it comes to handling JSON data. Every time I attempt a fetch request, I find myself needing to refer back to documentation due to the confusion surrounding JSON. Is there anyone ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...

Retrieve DirectionsResult data from a Google Maps URL

Currently, I am developing an updated tool that can transform Google Maps directions into GPX files. The initial version of this tool is performing quite well: it utilizes the Google Maps Javascript API (v3) to showcase a map on the website, allowing users ...