← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 2 of 7

Computed properties

A computed property is a value derived from other data that Vue caches until something it depends on changes.

In this page:

  1. Computed properties
Syntax
markup
export default {
  computed: {
    computedName() {
      return this.property * 2;
    }
  }
}

Computed properties

Define computed properties as functions that read reactive data and return a result. Vue tracks the dependencies and only recalculates when they change, unlike a method, which runs on every render. Writable computed properties use get and set.

Note: Use computed for derived values and methods for actions.

Example: Computed properties

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <p>{{ first }} {{ last }} => {{ fullName }}</p>
  <p>Total: {{ total }}</p>
</div>
<script>
  let runs = 0;
  Vue.createApp({
    data() { return { first: "Ada", last: "Lovelace", prices: [10, 20, 30] }; },
    computed: {
      fullName() { return this.first + " " + this.last; },
      total() { runs++; return this.prices.reduce((a, b) => a + b, 0); },
    },
  }).mount("#app");
  console.log("total getter executed once for 2 renders of the same value:", runs === 1);
</script>
</body>
</html>

<!-- Output:
Rendered: Ada Lovelace => Ada LovelaceTotal: 60
console: total getter executed once for 2 renders of the same value: true
-->
Live Example
Related Topics
Common Mistakes
  1. Using methods for expensive derived values
  2. Causing side effects inside computed
  3. Mutating data inside a computed getter
Chapter Summary
  • Computed values are derived and cached
  • They recompute when dependencies change
  • Methods run every call
  • Avoid side effects in computed
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.