Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I handle events in Vuex?

I am used to using a global event bus to handle cross-component methods. For example:

var bus = new Vue(); ... //Component A bus.$emit('DoSomethingInComponentB'); ... //Component B bus.$on('DoSomethingInComponentB', function(){ this.doSomething() }) 

However, I am building a larger project, which requires global state management. Naturally, I want to use Vuex.

While this bus pattern works with Vuex, it seems wrong. I have seen Vuex recommended as a replacement for this pattern.

Is there a way to run methods in components from Vuex? How should I approach this?

like image 306
Aaa Avatar asked Mar 15 '17 23:03

Aaa


People also ask

How do I add event listeners to Vue?

To add an event listener to a component using the v-on directive with Vue. js, we should add the native modifier. to set the add the native modifier to @click and set it to buttonClickHandler . Then buttonClickHandler will run when we click on the router-link component.

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

What is difference between mutation and action in Vuex?

Mutations are intended to receive input only via their payload and to not produce side effects elsewhere. While actions get a full context to work with, mutations only have the state and the payload .


1 Answers

Vuex and event bus are two different things in the sense that vuex manages central state of your application while event bus is used to communicate between different components of your app.

You can execute vuex mutation or actions from a component and also raise events from vuex's actions.

As the docs says:

Actions are similar to mutations, the difference being that:

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.

So you can raise an event via bus from actions and you can call an action from any component method.

like image 112
Saurabh Avatar answered Oct 05 '22 22:10

Saurabh