Episode 9 of 44

Computed Properties

Use computed properties for derived values — cached, efficient alternatives to methods for data that depends on other data.

Computed Properties

Computed properties are cached, derived values that automatically update when their dependencies change. They are ideal for transformations and calculations that depend on reactive data.

Computed vs Methods

new Vue({
    el: '#app',
    data: {
        age: 20
    },
    computed: {
        ageCategory() {
            return this.age < 18 ? 'Minor' : 'Adult';
        }
    },
    methods: {
        ageCategoryMethod() {
            return this.age < 18 ? 'Minor' : 'Adult';
        }
    }
});
<!-- Computed — no parentheses, cached -->
<p>{{ ageCategory }}</p>

<!-- Method — parentheses required, re-runs every render -->
<p>{{ ageCategoryMethod() }}</p>

Why Caching Matters

FeatureComputedMethod
CachingYes — only re-runs when dependencies changeNo — re-runs on every render
Called withNo parentheses: {{ total }}Parentheses: {{ total() }}
Use caseDerived/transformed dataActions, side effects, event handlers

If age does not change, the computed property returns its cached value without re-computing. A method would run the function from scratch every time the component re-renders — even if age has not changed.

Practical Example

data: {
    characters: ['Mario', 'Luigi', 'Yoshi', 'Toad'],
    search: ''
},
computed: {
    filteredCharacters() {
        return this.characters.filter(c => {
            return c.toLowerCase().includes(this.search.toLowerCase());
        });
    }
}
<input v-model="search" placeholder="Search...">
<ul>
    <li v-for="c in filteredCharacters">{{ c }}</li>
</ul>

Key Takeaways

  • Computed properties are cached — they only re-evaluate when their dependencies change
  • Use computed for derived data, methods for actions and event handlers
  • Access computed properties like data — no parentheses needed
  • They are ideal for filtering, sorting, and transforming data