Getters

Try this lesson on Scrimba

Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them:

  1. computed: {
  2. doneTodosCount () {
  3. return this.$store.state.todos.filter(todo => todo.done).length
  4. }
  5. }

If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal.

Vuex allows us to define “getters” in the store. You can think of them as computed properties for stores.

WARNING

As of Vue 3.0, the getter’s result is not cached as the computed property does. This is a known issue that requires Vue 3.1 to be released. You can learn more at PR #1878.

Getters will receive the state as their 1st argument:

  1. const store = createStore({
  2. state: {
  3. todos: [
  4. { id: 1, text: '...', done: true },
  5. { id: 2, text: '...', done: false }
  6. ]
  7. },
  8. getters: {
  9. doneTodos (state) {
  10. return state.todos.filter(todo => todo.done)
  11. }
  12. }
  13. })

Property-Style Access

The getters will be exposed on the store.getters object, and you access values as properties:

  1. store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getters will also receive other getters as the 2nd argument:

  1. getters: {
  2. // ...
  3. doneTodosCount (state, getters) {
  4. return getters.doneTodos.length
  5. }
  6. }
  1. store.getters.doneTodosCount // -> 1

We can now easily make use of it inside any component:

  1. computed: {
  2. doneTodosCount () {
  3. return this.$store.getters.doneTodosCount
  4. }
  5. }

Note that getters accessed as properties are cached as part of Vue’s reactivity system.

Method-Style Access

You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

  1. getters: {
  2. // ...
  3. getTodoById: (state) => (id) => {
  4. return state.todos.find(todo => todo.id === id)
  5. }
  6. }
  1. store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Note that getters accessed via methods will run each time you call them, and the result is not cached.

The mapGetters Helper

The mapGetters helper simply maps store getters to local computed properties:

  1. import { mapGetters } from 'vuex'
  2. export default {
  3. // ...
  4. computed: {
  5. // mix the getters into computed with object spread operator
  6. ...mapGetters([
  7. 'doneTodosCount',
  8. 'anotherGetter',
  9. // ...
  10. ])
  11. }
  12. }

If you want to map a getter to a different name, use an object:

  1. ...mapGetters({
  2. // map `this.doneCount` to `this.$store.getters.doneTodosCount`
  3. doneCount: 'doneTodosCount'
  4. })