2
votes

As I understand, the point of vuex is to guarantee the consistency of state, by exposing it to components only through mutations/actions/getters.

However, components can directly manipulate $store.state without using mutations/actions - potentially making the state inconsistent.

Why is vuex state exposed directly?

1
you can bind directly to the state.... but also be aware, if you get the state via a getter, you can still change it outside of a mutationKeith Nicholas
I think you'll find that attempting to alter $store.state won't actually change itPhil

1 Answers

5
votes

Using mutations / actions / getters etc is a suggested best practice but doesn't mean it has to be followed.

It could be that you just want to read a value from the state at which point it might be a little over-kill to write a getter for it.

I personally always try to use actions / getters to keep things consistent as it can get messy when you start mutating the state without a centralised system.

An example would be if you had a user module in the state. You might be tempted to just need the username so $store.state.user.username but I would always prefer to expose the user via getUser and access it on the component via user.username.

A pro for being able to access the state directly is a watch:

watch: {
  '$store.state.user' (to, from) {
    console.log('I changed!')
  }
}

This would allow you to know whenever the user state changed but again, if you used $this.$store.dispatch('setUser', myUser) you could do the same in the action.

I think the key here is be consistent, pick a way and use it but following best practice is always recommended.