Computed Properties

View saved

Why computed

Computed properties cache until dependencies change. Prefer them over methods for derived display values used in templates.

Define a computed value

Import computed and return the derived result.

<script setup>
import { ref, computed } from "vue";

const items = ref([
  { text: "Learn Vue", done: true },
  { text: "Build an app", done: false },
]);

const remaining = computed(() => {
  return items.value.filter((item) => !item.done).length;
});
</script>

<template>
  <p>{{ remaining }} left</p>
</template>

Read-only by default

A basic computed is a getter. Writeable computeds exist but are advanced—start read-only.

Computed vs methods

  • Computed caches; methods re-run every render when called
  • Use computed for derived state
  • Use methods for actions and event handling

Comments

One comment per signed-in account. Comments are saved with this page’s URL.