Can an event be passed from one Vue.js component to another without relying on a global EventBus?

I have two independent components that are not directly related to each other. However, I want them to be able to communicate so that when an event is triggered in one component, the other component can respond accordingly.

For example, let's consider a component named "reset-component" which emits an event called "reset".

<reset-component @reset="actionReset" />

Additionally, we have a "grid-component" that needs to listen for the "reset" event emitted by the "reset-component" and take specific actions in response.

<grid-component />

What are my options for achieving this functionality? The only approach I've thought of involves emitting a global event using an EventBus and then having the grid-component listen for that global event. But is this considered a best practice? Or could it actually be seen as an anti-pattern?

// Reset component
EventBus.$emit('reset')

// Grid component
created()
{
    EventBus.$on('reset', () => {
        doSomething()
    })
}

Answer №1

To achieve this, you can utilize the power of Subject. For a detailed guide on how to do this, check out the following resource: Vue.js + RxJS - Communicating Between Components with Observable & Subject

Answer №2

There are actually several options available to you. One of the possibilities, as you have already pointed out, is using a global event bus.

In your main file (let's say main.js), you could implement it like this:

Vue.prototype.$bus = new Vue()

Once you have done this, you will be able to access this.$bus in all of your components. For example:

methods: {
  dispatchReset () {
    this.$bus.$emit('reset')
  }
}

Other components can then listen for this event through:

created () {
  this.$bus.$on('reset', this.doReset)
}

Another suggestion that has been brought up is Vuex, as mentioned by @Armen Armus in the comments. With Vuex, you can manage a global state for your application and trigger events from any component. However, if you only need a few events like a reset, adding Vuex may not be necessary.

Alternatively, you could also store a "state" in your root Vue instance/component. But keep in mind, this approach would require passing props down and triggering events up from each view/component, which could become cumbersome.

Answer №3

When it becomes challenging to pass props to child components and raise events to parent components due to distance or app complexity, VueX comes in handy: Check out more about VueX here

Answer №4

Absolutely, you have the ability to utilize vm.$on and vm.$emit within components.

Within your reset-component, trigger the event from any method or element.

this.$emit('reset')

Subsequently, you can listen for it as follows:

<reset-component @reset="actionReset" />

Answer №5

In addition, you have the option to simply include hooks in the instances:

ResetComponent.$on("reset", performAction)

vm.$on

However, I presume this may establish a connection.

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

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

Deploy your Vue.js project using Jenkins for seamless integration

I am new to Jenkins and have successfully completed a few builds/deployment jobs of .net projects. Now I am attempting to build/deploy a Vue.js project through Jenkins, but I am facing difficulties... I can build the project directly on a server using th ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

Creating a responsive slider in CSS that matches this specific design

Looking to create a responsive sidebar based on this specific design Link to design on Figma Key focus is implementing the "< 4/12 >" functionality and ensuring it is responsive Current code can be found here: Code on JSFiddle enter code ...

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

Creating a compact array from a larger array in JavaScript

I am currently using the jquery.bracket library and I am looking to split a large array into pairs like ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] from var all= ["'Team 1', 'Team 2'","'T ...

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

Using j Query to create custom masks for various formats with the option to include optional digits

Looking for a way to mask the CVV card number..! The masking should allow for either 3 numbers like xxx 123 or 4 numbers like xxxx 4567 I have attempted to implement this with jQuery mask plugin, but it only allows for 4 characters. How can I enable both ...

VueJS is unable to identify the variable enclosed within the curly braces

I recently started learning VueJS and I've hit a roadblock. My goal is to display a variable, but for some reason, instead of seeing the product name, all I get is {{product}} Here's the HTML code I'm using: <!DOCTYPE html> <html l ...

When using the * selector in jQuery on Chrome, it targets and selects scrollbars

Here's the code I'm currently using: $("*").bind("mousedown.sg", { 'self':this }, this.sgMousedown); This code binds an event listener to all elements on the page, and it functions properly in most browsers except for Chrome. In Chrom ...

Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu. So far, they have been able to use ajax to send requests and generate a sub-menu. However, ...

Unlocking the value of the "input" field within an EventListener function in Angular directly from the DOM

In my "characters" module, there is a form with a text field and a button. When the button is clicked, it triggers a function but I am struggling to retrieve the current input text and pass it to the async function. HTML: TS: Unfortunately, simply getti ...

The controller function is not triggered if the user does not have administrator privileges

I have a code snippet in which my controller function is not being triggered for users who do not have the role of "Admin". Can someone help me identify where I went wrong? Just to clarify, the controller function works fine for users with the role of "Adm ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if tod ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

Show/Hide Row in Material-UI DataGrid

I need assistance with expanding lines in Material UI. I am trying to create drop-down rows in my table (individually for each row) within a table built using Material UI. Despite researching extensively online, I have been unable to achieve consistent res ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...