0
0
Vueframework~5 mins

Getters for computed store values in Vue

Choose your learning style9 modes available
Introduction

Getters let you create values that update automatically when your store data changes. They help keep your app data organized and easy to use.

You want to show a total count based on items in your store.
You need to filter a list of products by category stored in your state.
You want to combine multiple pieces of store data into one value.
You want to avoid repeating the same calculation in many components.
Syntax
Vue
const store = createStore({
  state() {
    return { count: 0 }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }
})

Getters receive the current state as their first argument.

They behave like computed properties and update automatically.

Examples
This getter returns the square of the count.
Vue
getters: {
  squaredCount(state) {
    return state.count ** 2
  }
}
This getter returns true if count is positive.
Vue
getters: {
  isPositive(state) {
    return state.count > 0
  }
}
This getter combines first and last name from state.
Vue
getters: {
  fullName(state) {
    return `${state.firstName} ${state.lastName}`
  }
}
Sample Program

This example creates a store with a count of 5. The getter doubleCount returns twice that value. When we log it, we see 10.

Vue
import { createStore } from 'vuex'

const store = createStore({
  state() {
    return {
      count: 5
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  }
})

console.log(store.getters.doubleCount)
OutputSuccess
Important Notes

Getters are cached and only recalculate when their dependencies change.

You can access getters in components or other parts of your app via the store.

Summary

Getters compute values based on store state.

They update automatically when state changes.

Use getters to keep your data logic clean and reusable.