← Back to all tutorials
Vuex TutorialEpisode 4

Using Computed Properties

Use computed properties to reactively access store state in components — keep templates clean and responsive to state changes.

Using Computed Properties

You should always access store state through computed properties — not directly in the template. This ensures components react to state changes and keeps your templates clean.

Why Computed Properties?

<!-- Works, but not recommended -->
<p>{{ $store.state.products.length }}</p>

<!-- Better — use a computed property -->
<p>{{ productCount }}</p>

computed: {
    productCount() {
        return this.$store.state.products.length;
    }
}

Computed properties are cached and only re-evaluate when their dependencies change. They also keep your template cleaner — productCount is more readable than $store.state.products.length.

Multiple Computed Properties

export default {
    computed: {
        products() {
            return this.$store.state.products;
        },
        productCount() {
            return this.$store.state.products.length;
        },
        totalPrice() {
            return this.$store.state.products.reduce((total, p) => total + p.price, 0);
        }
    }
};

Using in the Template

<template>
    <div class="sidebar">
        <h3>Summary</h3>
        <p>Total products: {{ productCount }}</p>
        <p>Total price: ${{ totalPrice }}</p>
        <ul>
            <li v-for="product in products" :key="product.id">
                {{ product.name }}
            </li>
        </ul>
    </div>
</template>

When State Changes

Store state changes
    ↓
Computed properties detect the dependency change
    ↓
Vue re-evaluates the computed properties
    ↓
Template re-renders with the new values

Because Vue's reactivity system tracks this.$store.state as a dependency, any mutation to the store automatically triggers re-computation and re-rendering in all components that use that state.

Key Takeaways

  • Always access store state through computed properties for reactivity and caching
  • Computed properties keep templates clean — use meaningful names instead of $store.state.x
  • They automatically update when the underlying store state changes
  • Multiple computed properties can derive different values from the same state