Search code examples
javascriptvue.jsvuex

Pass key to vuex getter to get diferent state


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.


Solution

  • 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