Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex: when to use state versus getters?

Tags:

vue.js

vuex

When retrieving data from Vuex, in some cases the choice between using getters and access state directly is quite clear. For example:

  • If I'm retrieving a simple scalar, such as the value of the count variable, accessing the state directly seems to make sense
  • If I'm retrieving a filtered list of item however, a getter is the clear choice.

But what about other cases where there is only a slight amount of logic required to retrieve a value? For example, what if I have a foo object in the root of my store, and:

  • I want to retrieve a value such as foo.option, but I'm not sure if it exists. I would usually use a ternary operator to check for the existence of the value, and either return the value or return null.
  • I want to retrieve foo.date, but date is a string so I want it converted to a moment.

Either of these needs could be met using a mapState function, but should I be using mapGetter instead? What's the difference?

like image 550
DatsunBing Avatar asked Nov 07 '22 04:11

DatsunBing


1 Answers

Either of these needs could be met using a mapState function

True... but what happens if more than 1 component needs the "slightly altered" value? You'd end up with duplicate logic. In that case perform the "slight amount of logic" in a getter.

like image 88
Eric Guan Avatar answered Nov 14 '22 23:11

Eric Guan