TExcelTAD
Home › Vue › Vue Computed Properties

Vue Computed Properties

Templates are meant to be simple. As soon as an expression in {{ }} grows — filtering a list, summing prices, combining names — it becomes hard to read and impossible to reuse. A computed property moves that logic into the component and gives the result a name.

js
computed: {
  fullName() {
    return this.firstName + ' ' + this.lastName;
  }
}

In the template you use it like ordinary data — without parentheses: {{ fullName }}.

A first computed property

html · try it yourself
<div id="app">
  <p><input v-model="first"> <input v-model="last"></p>
  <p>Full name: <strong>{{ fullName }}</strong></p>
  <p>Initials: <strong>{{ initials }}</strong></p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ first: 'Grace', last: 'Hopper' }),
    computed: {
      fullName() {
        return `${this.first} ${this.last}`.trim();
      },
      initials() {
        // a computed property can use other computed properties
        return this.fullName.split(' ').map(w => w[0] || '').join('').toUpperCase();
      }
    }
  }).mount('#app');
</script>

Vue knows that fullName depends on first and last, and that initials depends on fullName. Change either input and both update.

Computed values are cached

This is the big difference from methods. A computed property remembers its result and only recalculates when one of its reactive dependencies changes. Compare the logs:

html · try it yourself
<div id="app">
  <input v-model="note" placeholder="Unrelated input — type here">
  <p>Computed: {{ expensiveTotal }} | {{ expensiveTotal }}</p>
  <p>Method: {{ expensiveTotalMethod() }} | {{ expensiveTotalMethod() }}</p>
  <button @click="numbers.push(numbers.length + 1)">Add a number</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ numbers: [1, 2, 3, 4], note: '' }),
    computed: {
      expensiveTotal() {
        console.log('computed recalculated');
        return this.numbers.reduce((a, b) => a + b, 0);
      }
    },
    methods: {
      expensiveTotalMethod() {
        console.log('method ran');
        return this.numbers.reduce((a, b) => a + b, 0);
      }
    }
  }).mount('#app');
</script>

On the first render the computed runs once (although it's used twice), while the method runs twice. Typing in the unrelated input re-runs the method each time, but not the computed. Only adding a number invalidates the cache.

Computed property Method
Used in template as {{ total }} {{ total() }}
Cached ✅ until dependencies change ❌ runs on every render
Takes arguments ❌ no ✅ yes
Typical use Derived values (filtered lists, totals, formatted strings) Event handlers, actions

Filtering and sorting lists

Computed properties are the right way to display a filtered or sorted view of a list without changing the original data.

html · try it yourself
<div id="app">
  <input v-model="query" placeholder="Filter by name">
  <label><input type="checkbox" v-model="onlyAvailable"> In stock only</label>
  <select v-model="sortBy">
    <option value="name">Sort by name</option>
    <option value="price">Sort by price</option>
  </select>

  <ul>
    <li v-for="p in visibleProducts" :key="p.id">{{ p.name }} — ${{ p.price }}</li>
  </ul>
  <p>Showing {{ visibleProducts.length }} of {{ products.length }} products.</p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({
      query: '',
      onlyAvailable: false,
      sortBy: 'name',
      products: [
        { id: 1, name: 'Wireless Mouse', price: 25, stock: 4 },
        { id: 2, name: 'USB-C Cable', price: 9, stock: 0 },
        { id: 3, name: 'Keyboard', price: 49, stock: 7 },
        { id: 4, name: 'Monitor Stand', price: 35, stock: 0 },
        { id: 5, name: 'Webcam', price: 59, stock: 2 }
      ]
    }),
    computed: {
      visibleProducts() {
        const q = this.query.toLowerCase();
        return this.products
          .filter(p => p.name.toLowerCase().includes(q))
          .filter(p => !this.onlyAvailable || p.stock > 0)
          .sort((a, b) => this.sortBy === 'price'
            ? a.price - b.price
            : a.name.localeCompare(b.name));
      }
    }
  }).mount('#app');
</script>

Note that .filter() returns a new array, so .sort() does not reorder the original products. Never call .sort() or .reverse() directly on reactive source data inside a computed — use a copy ([...list].sort() or list.toSorted()).

Writable computed properties

Computed properties are read-only by default. If you need to assign to one, give it a get and a set:

html · try it yourself
<div id="app">
  <p><input v-model="fullName"> (edit me)</p>
  <p>first = "{{ first }}", last = "{{ last }}"</p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ first: 'Ada', last: 'Lovelace' }),
    computed: {
      fullName: {
        get() {
          return `${this.first} ${this.last}`;
        },
        set(value) {
          const [first, ...rest] = value.split(' ');
          this.first = first;
          this.last = rest.join(' ');
        }
      }
    }
  }).mount('#app');
</script>

Tip: Keep computed getters pure: compute and return a value, nothing else. No API calls, no changing other data, no DOM work. For side effects use a watcher (next lesson).

Note: In the Composition API the same idea is written as const fullName = computed(() => first.value + ' ' + last.value).

Test yourself

How do you display the computed property total in a template?

  1. {{ total() }}
  2. {{ total }}
  3. {{ computed.total }}
  4. {{ this.total() }}

When does a computed property recalculate?

  1. On every render
  2. Every second
  3. Only when one of its reactive dependencies changes
  4. Only when you call it with new arguments

Which of these belongs in a computed getter?

  1. Returning a filtered copy of a list
  2. Sending a fetch request
  3. Changing another data property
  4. Writing to localStorage