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
- Declaration: You define
computedproperties in your component's script section. - Reactivity:
computedproperties automatically track reactive dependencies (likepropsordata). - Cache Optimization: The value of a
computedproperty is cached and recalculated only when its dependencies update. - Usage:
computedproperties 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
- Reactive Dependency: The
fullNameis recalculated wheneverprops.firstNameorprops.lastNamechanges. - Efficient Caching: The
uppercaseTitleis computed once and only recomputed iftitle.valuechanges. - 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.