5
votes

On the official Vuex documentation and guides available on the internet, it is mentioned that in order to access your store state or getter, you have to create a computed property that returns the data you need (ex. this.$store.state.info), or you can use a MapState helper.

I access Vuex data on template referencing it directly on the template like this:

<p> {{ $store.state.info }} </p>

The same for getters. It works fine, but I wonder if I am making a mistake because all articles I have read about Vuex doesn't do like this. The guides always create a computed property directly using MapState or MapGetter.

Do you think it is fine the way I am doing or it is wrong and I might encounter a bug later in my project, it is just not a best practice or it is fine to use Vuex the way I do?

2
Vuex docs state when best to use the mapState helper: When a component needs to make use of multiple store state properties or getters, declaring all these computed properties can get repetitive and verbose. To deal with this we can make use of the mapState helper which generates computed getter functions for us, saving us some keystrokes. If your template contained only a few references to $store.state and it were easily readable, it's probably fine IMO. You won't encounter a bug just because you're not using the helpertony19
@edpr please consider choosing an answer or either adding further requirements to set for one.sab

2 Answers

5
votes

Vue actually isn't opinionated although that doesn't mean that there can't exist some -best practices-, in your case I see that your way is just fine, actually there are many approaches to do that in Vue, if your app is going to grow (medium to big size) then it's probably better to go for map helpers having maintainability in mind, although the trade off is a more verbose code.

edit: Update: @edpr I thought of another reason, may be evident or not but if you want to do everything the ES2015 way, then go for mapHelpers as you can benefit from destructuring and spread syntax on the fly, then you'd have less verbose result when going for the maps way.

1
votes

MapGetters or MapState are usually the best way, beacuse they provide convinient syntax that is easy to read and understand and automatically map your getters to a computed property. Also it is good to keep them in one place in case of large number of getters, actions etc.