How to use getters in Vuex

Vuex is the state management library for Vuejs.

Vuex makes use of a central state it uses to manage its store data.

If we intend to access this state object in a component, we could access it as such:

computed: {
  approvedUsers () {
    return this.$store.state.users.filter(user => user.approved)
  }
}

However, supposing we intend to use this method in other components, we would either need to extract it into a helper function and import it into all those components or follow the traditional way of copying and pasting.

getters to the rescue

This is where Vuex getters become handy. We implement our getter function in the Vuex store and call it in all the components we need it.


const store = new Vuex.Store({
  state: {
    users: [
      { id: 1, approved: false, username: "Joe" },
      { id: 2, approved: true, username: "Tim" }
    ]
  },
  getters: {
    approvedUsers: state => {
      return state.users.filter(user => user.approved)
    }
  }
})

Accessing it in a component

To access it in the component of our choice, we call the $this.store.getters helper :

computed: {
  approvedUsers () {
    return this.$store.getters.approvedUsers
  }
}

Using the mapGetters helper

We can also use the mapState helper, which allows us to get rid of the many $this.store.getters in the computed property.

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'approvedUsers'
    ])
  }
}

Thanks for reading!

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources