I've had this question buried in my mental Rolodex for quite some time now. I'm running a very complex Vue application that deals with quite a number of components that must communicate so for that I use a very structured setup of Vuex
utilizing its module
system. However, for a particular group of components, say a comments
folder, i.e:
Comments Directory:
Is it fine to utilize a reserved Event Bus
placed in this directory only for these 3 components to communicate to one other, or is that deemed as "malpractice" since I already have a large vuex system going ?
I suggest using Vuex for all of your application. Doing so keeps your state in a single place. Using an event bus detracts from this, in that now you have two places containing state. Worse still, an event bus is less maintainable and often breaks the "one way data flow" promoted by Vue and Vuex (and other Flux implementations).
Vuex can be used for both application state and application data. Data being the usual stuff like customer details, etc. State being the "this sidebar hamburger menu is open" or "this modal is open" or "user selected this item in a list".
This then leads on to your "I just feel as Vuex should be used for app wide communications, not for communications between 2-3 neighbouring components". It's the same thing when you think about it.
If a parent component wishes to communicate with a child component, it passes props down. If the child wishes to communicate in a decoupled manner it emits events. That is perfectly fine for that scenario.
Try doing that with multiple nested components! A -> B -> C -> D
Imagine if D needed to update some state in B. How do you do that, emit events all the way up, and couple your components? Yuck, that is not the way to go. D should dispatch a Vuex action which in turn updates B via the store binding. What about when A needs to updated something in C? Now your B component needs special case extra props just to allow A to communicate with C when B should be able to exist on it's own without A as a parent. Yuck again! Dispatch an action.
Communicating between sibling components or even components in totally different parts of the page is exactly one of the things Vuex is designed for: application state.
Removing your event bus and accepting this approach will make your code easier and more maintainable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With