0
0
VueConceptBeginner · 3 min read

What is Getter in Vuex: Explanation and Example

In Vuex, a getter is a function that computes and returns derived state from the store's data. It acts like a computed property for the Vuex store, letting you access filtered or calculated data easily and reactively.
⚙️

How It Works

Think of Vuex getters as special windows into your store's data that can show you exactly what you need without changing the original data. Just like how you might look through a window to see a filtered view of a garden, getters let you see a processed or computed version of your store's state.

When you define a getter, it receives the store's state and can return a value based on it. This value updates automatically when the state changes, similar to how computed properties work in Vue components. This means you don't have to manually recalculate values or filter data every time you want to use it.

Getters help keep your components clean by moving logic that derives data out of the components and into the store, making your app easier to maintain and understand.

💻

Example

This example shows a Vuex store with a getter that returns all completed tasks from a list.

javascript
import { createStore } from 'vuex'

const store = createStore({
  state() {
    return {
      tasks: [
        { id: 1, title: 'Learn Vuex', completed: true },
        { id: 2, title: 'Build app', completed: false },
        { id: 3, title: 'Test app', completed: true }
      ]
    }
  },
  getters: {
    completedTasks(state) {
      return state.tasks.filter(task => task.completed)
    }
  }
})

// Usage example:
console.log(store.getters.completedTasks)
Output
[{ id: 1, title: 'Learn Vuex', completed: true }, { id: 3, title: 'Test app', completed: true }]
🎯

When to Use

Use getters when you need to get data from the Vuex store that requires some calculation or filtering before use. For example, if you want to show only active users, count items, or combine multiple pieces of state into one value, getters are the right choice.

They are especially helpful when multiple components need the same derived data, so you avoid repeating the same logic in many places. This keeps your app consistent and easier to update.

Key Points

  • Getters are like computed properties for Vuex store state.
  • They return derived or filtered data without changing the original state.
  • Getters update reactively when the state changes.
  • Use getters to keep your components simple and avoid repeating logic.

Key Takeaways

Getters provide computed views of Vuex store state for easy access.
They help keep component code clean by centralizing data logic in the store.
Getters update automatically when the underlying state changes.
Use getters to share derived data across multiple components efficiently.