Builder

Computed in Custom Component

Overview

In a custom component, computed properties are used to create reactive, derived values based on the component's state or props. These values are cached and recomputed only when their dependencies change, making them highly efficient for calculations or transformations that depend on reactive data.

How computed Works in a Custom Component

  1. Declaration: You define computed properties in your component's script section.
  2. Reactivity: computed properties automatically track reactive dependencies (like props or data).
  3. Cache Optimization: The value of a computed property is cached and recalculated only when its dependencies update.
  4. Usage: computed properties can be used in templates or other parts of the script, just like regular reactive data.

For example

<template>
  <div>
    <p>Full Name: {{ fullName }}</p>
    <p>Uppercase Title: {{ uppercaseTitle }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

// Props
const props = defineProps({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  title: { type: String, required: false }
});

// Reactive data
const title = ref(props.title || 'Default Title');

// Computed properties
const fullName = computed(() => `${props.firstName} ${props.lastName}`);
const uppercaseTitle = computed(() => title.value.toUpperCase());
</script>

Key Points

  1. Reactive Dependency: The fullName is recalculated whenever props.firstName or props.lastName changes.
  2. Efficient Caching: The uppercaseTitle is computed once and only recomputed if title.value changes.
  3. Simplifies Logic: Moves complex logic or transformations out of templates and into the script.

When to Use computed

  • When you need to derive values from reactive data or props.
  • For values that are reused multiple times, ensuring performance through caching.
  • When the derived data depends on other reactive data and must update automatically.

Copyright © 2026