2

In vuex store there is many similar states:

const state = {
  count: 0,
  count2: 1,
  count3: 2
};

and for every state there is a corresponding getter:

const getters = {
  getCount: (state) => state.count,
  getCount2: (state) => state.count2,
  getCount3: (state) => state.count3,
};

Is there a way to turn these 3 in one dynamic getter who would accept the key and get the corresponding data.

Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46

3 Answers3

3

You could create another getter, and use another function to pass the parameter.

const getters = {
  getCount: (state) => state.count,
  getCount2: (state) => state.count2,
  getCount3: (state) => state.count3,
  // The param could be "count" || "count2"
  getAllCount: (state) => (param) =>  state[param] 
  // and calling
  this.$store.getters['getAllCount'](theParamKey)
};
Woohaik
  • 1,084
  • 1
  • 6
  • 24
2

You have two options, first, you could return a function from the getter as explained here, or, and that would make more sense in many situations, you could just change the state and return an object (or an array):

const state = {
  count: {
    count1: 0,
    count2: 1,
    count3: 2,
  }
};

const getters = {
  getCount: (state) => state.count,
};

In my experience, the second option is usually the best one, both because it's easier for other developers and maintenance (returning a function from a getter is quite counter-intuitive) and because it's super easy to handle objects (or arrays), but surely the first option has its use-cases too.

Lazza
  • 91
  • 4
1

We have a way to pass arguments to a getters function Here is how you do it

const getters = {
  getCount: (state) => (arg) => {
    return state[arg]; // where arg can be count or count1 or count2
  }
}

Reference link: https://vuex.vuejs.org/guide/getters.html#method-style-access

Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
Amaarockz
  • 4,348
  • 2
  • 9
  • 27