← Back to all tutorials
Vuex TutorialEpisode 5

Getters

Define getters in the Vuex store — centralized computed properties that any component can access for derived state.

Getters

In the previous episode, each component created its own computed properties to derive values from state. If multiple components need the same derived value, you would duplicate the logic. Getters solve this — they are computed properties defined in the store, available to all components.

Defining Getters

// store/store.js
export const store = new Vuex.Store({
    state: {
        products: [
            { id: 1, name: 'Banana Skin', price: 20 },
            { id: 2, name: 'Shiny Star', price: 40 },
            { id: 3, name: 'Green Shells', price: 60 },
            { id: 4, name: 'Red Shells', price: 80 },
            { id: 5, name: 'Mushroom', price: 15 }
        ]
    },
    getters: {
        saleProducts(state) {
            return state.products.map(product => {
                return {
                    ...product,
                    price: product.price / 2
                };
            });
        },
        productCount(state) {
            return state.products.length;
        },
        totalPrice(state) {
            return state.products.reduce((total, p) => total + p.price, 0);
        }
    }
});

Each getter receives state as its first argument. Getters can also receive other getters as a second argument.

Getters That Use Other Getters

getters: {
    productCount(state) {
        return state.products.length;
    },
    averagePrice(state, getters) {
        return getters.totalPrice / getters.productCount;
    }
}

Accessing Getters in Components

computed: {
    saleProducts() {
        return this.$store.getters.saleProducts;
    },
    productCount() {
        return this.$store.getters.productCount;
    }
}

Using in the Template

<template>
    <div>
        <h2>Sale Products (50% off!)</h2>
        <div v-for="product in saleProducts" :key="product.id">
            <span>{{ product.name }} — ${{ product.price }}</span>
        </div>
        <p>Total items: {{ productCount }}</p>
    </div>
</template>

Getters vs Component Computed

FeatureStore GettersComponent Computed
Where definedIn the Vuex storeIn the component
Accessible fromAny component via this.$store.gettersOnly the component where defined
Use whenMultiple components need the same derived valueOnly this component needs the value
CachedYes — based on state dependenciesYes — based on reactive dependencies

Key Takeaways

  • Getters are the store's computed properties — derived values from state
  • They receive state (and optionally getters) as arguments
  • Access them with this.$store.getters.getterName
  • Use getters when multiple components need the same derived data — avoids duplication