Vuex is quite a powerful way of storing variables and sharing them across components, but where do you draw the line? Which variables do you store locally and which of them are shifted to Vuex store?
This is the advise I often come across -
- Get your variables in store; keep component clean and consider future reuse
- Don’t overdo Vuex. Apply judgment and use store judiciously
I find that the code I write oscillates between the two with no practical standard that I can apply across the team.
So, these are the instructions that we try to follow -
Store hyper local variables local
Variables that do not find use in other components even if you so desire. They absolutely make no sense anywhere but in the specific UI component.
- Form validation variable on a specific variable, which specify whether form is valid and used by VeeValidate
- Variables used in local filter or local functions, and also used by the UI
- Variables holding values that are extracted or format-changed from the larger data set. For e.g. “chart refreshed on:
<locale format date>”
These go in
data section for the most part, and in
All server calls in store
Any HTTP requests (and even GraphQL requests) will be done in methods in a store, and request/result stored as state variables. These will go in
computed within a component.
Shared variables need to go in store
Even if there is variable sharing between two components, the variables are not treated as
props but will be moved to store instead.
Variables used during mutations go to store
For e.g. we tend to map values from UI to a PATCH request input. These variables are often treated locally, but we end up using same or similar logic across UI components sooner or later. So, store.
So, in conclusion - there is no single conclusion
I “try” to not over-engineer solutions and move variables to store, but at the same time I don’t think I can help it. I keep coding for a requirement that starts from moon, and keeps changing direction as I showcase wireframes and talk through process flows.
I just love this life.