How should I handle events in Vuex?

前端 未结 2 1125
广开言路
广开言路 2021-01-31 17:08

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\         


        
相关标签:
2条回答
  • 2021-01-31 17:37

    Using a global event bus is an anti pattern because it becomes very difficult to trace it (where was this event fired from? Where else are we listening to it? etc.)

    Why do you want to use a global event bus? Is there some method that you want to trigger in another component? If you use Vuex then all your actions (methods) are in one central state and you can just dispatch your action.

    So for example instead of doing this..

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

    With Vuex you would have the doSomething() function in a central store as an action. Then just make sure to convert you local component data to a global Vuex state data and dispatch that action.

    this.$store.dispatch('doSomething')
    
    0 讨论(0)
  • 2021-01-31 17:44

    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.

    0 讨论(0)
提交回复
热议问题