SoFunction
Updated on 2025-04-05

Getter explanation of Vuex introduction

1. Introduce Getter

Sometimes we need to derive some state from the state in the store, such as filtering the list and counting:

computed: {
  doneTodosCount () {
    return this.$(todo => ).length
  }
}

If there are multiple components that require this property, we either copy the function, or extract a shared function and import it in multiple places - either way is not ideal.

Vuex allows us to define getters (which can be considered as computed properties of the store). Just like computed properties, the return value of getter is cached according to its dependencies and will be recalculated only if its dependencies change.

getter is similar to the getter method we define in the java entity class.

Getter accepts state as its first parameter:

const store = new ({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return (todo => )
    }
  }
})

2. Access getter through attributes

Getters are exposed as objects, and you can access these values ​​as properties:

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

Getter can also accept other getters as the second parameter:

getters: {
  doneTodosCount: (state, getters) => {
    return 
  }
}
 // -> 1

We can easily use it in any component:

computed: {
  doneTodosCount () {
    return this.$
  }
}

Note that getters are cached as part of Vue's responsive system when accessed through properties.

3. Access through methods

You can also pass parameters to getter by letting getter return a function. Very useful when you query arrays in the store.

getters: {
  getTodoById: (state) => (id) => {
    return (todo =>  === id)
  }
}
(2) // -> { id: 2, text: '...', done: false }

4. mapGetters helper function

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

import { mapGetters } from 'vuex'

export default {
  computed: {
    // Use the object expansion operator to mix getter into the computed object    ...mapGetters([
      'doneTodosCount',
      'anotherGetter'
    ])
  }
}

If you want to give another name to a getter property, use the object form:

...mapGetters({
  // Map `` to `this.$`  doneCount: 'doneTodosCount'
})

This is the end of this article about Getter's detailed explanation of Vuex introduction. For more related Getter content on Vuex, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!