DEV Community

Discussion on: Architecting Vuex store for large-scale Vue.js applications

Collapse
 
psnehanshu profile image
Snehanshu Phukon

Nice article Musthaq.
Can you please elaborate on why we should use getters instead of directly accessing state properties?

Collapse
 
nkoik profile image
Nikos Koikas

Cause you could return a filter or map or whatever you want from state property in vuex and not in component privately

Collapse
 
haxzie profile image
Musthaq Ahamad • Edited

There is a good chance that you might actually try to mutate it outside the store. The store object should be treated as an immutable object and should only be mutated inside the mutation handlers. Since we have used strict: true in our main store file. Vuex will actually throw errors when you try to mutate it outside the mutation handlers. You will likely come across this error a lot if you try to mutate it outside ~ Do not mutate vuex store state outside mutation handlers.

Considering this, it's in our best interest to expose only the getters outside the store :)

Collapse
 
psnehanshu profile image
Snehanshu Phukon

I understand that, we shouldn't mutate state outside of mutations. But mutating is one thing and reading is different. What I am concerned with is reading. I can directly read store object from this.$store.state, so why do you think it is a good practice to use getters?

Thread Thread
 
haxzie profile image
Musthaq Ahamad

It is totally fine to use this.$store.state, or mapState to map the state properties into a component. But, considering the chances that these might get referenced or mutated, we can take a safe stand. Using getters too much is also a problem since they are actually computed properties for your store they need a bit of extra computation. The pro side of using getters is that we can move more of the logic, (if any involved in processing the state properties) inside your getters and have a safe stand on preventing it from getting mutated.

Collapse
 
shreshthmohan profile image
Shreshth Mohan

This probably is the best post explaining when and when not to use getters. You can simply use mapState to access state properties directly.

codeburst.io/vuex-getters-are-grea...