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 rescueThis 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)
}
}
})
To access it in the component of our choice, we call the $this.store.getters
helper :
computed: {
approvedUsers () {
return this.$store.getters.approvedUsers
}
}
mapGetters
helperWe 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!