Best Alternative to Bus Events in Vue
Every web app needs to interact with a server. Our responsibility, frontend devs, is to optimize this relationship and not overload the server with multiple, simultaneous calls while rendering our components.
More often than not, some components, which request data from the server, are mounted in different places. The most delicate part is when these components are on the same page, and they all make their request at the same time.
A couple of days ago, I tried to find an alternative solution to Bus Events for communicating between components. I did not find a single one. At this point, my co-worker and friend Derwyn and I started working on something. If you are familiar with the Bus concept and know the issue well enough, go to number 4. Otherwise, I'll describe a hypothetical situation, explain the problem and then share our solution.
1. Laying out an Example:
Imagine a straightforward layout with a multi-row table. Some columns get the server's reference data such as:
Suppose Make, and Model are foreign keys in your DB, and you built a component that receives the endpoint as a prop to get both make or model data from the server and renders any name that comes in it. So, to display them, you should get 3 data packages:
A- The team member's name, make and model ids:
B- Make names:
C- Model names:
Then you could combine all the data into the table.
2. Exposing the Problem:
From the example above, the name displaying component would make 5 Make data requests and 5 Modal data requests.
Needless to say, the application will have a poor performance, overload the server, slow down the browser and, among other issues, might freeze and become unresponsive.
We need some tools to communicate between components.
3. The Common Solution
If you are a Vue developer, you have probably seen this solution to this issue before. You can easily find examples and tutorials on the web about Bus Events. If you are unfamiliar with this concept, look at this article.
However, it's also known that Bus Events has some downsides, some gotchas, and may cause different issues; some of them are hard to debug.
Vue js docs discourage using it so that $on, $off and $once were removed from Vue 3.
Ok, I got it. What is the solution, then? My buddy and I created a data request Vuex store to handle server calls.
4. An Alternative to Events
The following is a Vuex store in TS to handle data calls.
This store does not intend to make everything a Bus Event is capable of, but it substitutes a great deal of it. While a lot is happening under the hood within Bus, this is in plain sight and easily debugged.
However, it has not been battle tested yet and is still in development. Updates and improvements will be posted at a later time.