Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vuejs
vuex
javascript
communitycreator
getters

How to use getters in Vuex

Chibuike Nwachukwu

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!

RELATED TAGS

vuejs
vuex
javascript
communitycreator
getters
RELATED COURSES

View all Courses

Keep Exploring