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

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

How can you show a top-level component across various routed pages in Nuxt without having to reload it each time?

Recently starting a new job, I have been tasked with creating a website using nuxt. In a typical nuxt layout file, the structure would look something like this: <NavMenu /> <Nuxt /> - various routed pages <Footer /> When transitioning be ...

What is the best way to choose the right value based on parameters?

I am currently working on a solution using protractor where I have several options to consider. Specifically, I need to test timeslots between 1600 and 1900, along with an else statement. For instance, if the 1600 timeslot is selected, then the code shoul ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

Mastering the art of using componentWillUnmount() in ReactJs

According to the official tutorial: componentWillUnmount() is called right before a component is removed and destroyed. It's used for any necessary cleanup tasks like stopping timers, cancelling network requests, or cleaning up DOM elements that we ...

Having trouble with the npm Twitter API functionality?

I'm attempting to execute a simple stream using an example code snippet. Here is the code I am working with: var twit = require('twitter'); var twitter = new twit({ consumer_key: '[KEY]', consumer_secret: &ap ...

Replicate the function of the back button following the submission of an ajax-submitted form to Preview Form

I am currently working on a multi-part form with the following data flow: Complete the form, then SUBMIT (using ajax post) jQuery Form and CodeIgniter validation messages displayed if necessary Preview the submitted answers from the form Options: Canc ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

Encountering difficulties with a GraphQL structure within Apollo framework

I am currently in the process of building an Express server using Apollo 2. My schema is as follows: const typeDefs = gql `{ type Movie { id: ID! title: String year: String rating: String } type Query { ...

Deactivate fields B and C unless input A is provided

http://jsfiddle.net/6Pu3E/ JavaScript Code: $(document).ready(function() { var block = false; if ($('#password').attr('disabled')) { block = false; } else { block = true; } if (block) { $(&a ...

Troubleshooting: Issues with VueJS Class Binding Functionality

In my form, I have an input field that is validated to check if it is empty or not. If the input field is empty, a red border is applied using class binding. However, when the user focuses on the input field after receiving the error, the error message sh ...

What could be causing the NextJS query string to be undefined upon reloading the page?

I am currently working on a NextJS application where I have created a search results page that relies on a query parameter being passed. To grab the query string, I am using the next/router package. The issue I am facing is that after the initial load of t ...

The pages are constantly showing an error message that reads, "There is a problem with the SQL syntax in your code."

I am having trouble with my login page as it is displaying an error on my index.php file. Below is the code snippet from my index.php: <?php include('supsrwk_epenyenggaraan.php'); ?> <?php if (!function_exists("GetSQLValueString")) { f ...

Switching between TWO classes in Vuejs

I've been grappling with how to add or remove TWO classes in Vue JS for hours. The documentation examples only demonstrate toggling one class. My goal is to change a button's class to either: active toggle-on or toggle-off when clicked. While ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

Bootstrap 4: Popper not found - ReferenceError in the script

After setting up Bootstrap 4 using Node and Gulp, I encountered an error when running the application: Uncaught ReferenceError: Popper is not defined So far, I've only utilized the Bootstrap grid system and have not delved into the Bootstrap JS fu ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...