How should I handle events in Vuex?

梦想的初衷 提交于 2019-12-03 05:43:58

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42822948/how-should-i-handle-events-in-vuex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!