Home > Mobile >  Pass key to vuex getter to get diferent state
Pass key to vuex getter to get diferent state

Time:11-03

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.

CodePudding user response:

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)
};

CodePudding user response:

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.

  • Related