JAVASCRIPT

Efficient Derived State with Vue 3 Computed Properties

Utilize Vue 3's `computed` properties in the Composition API to create cached, reactive values derived from other reactive data.

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

const firstName = ref('Jane');
const lastName = ref('Doe');
const quantity = ref(2);
const unitPrice = ref(10.50);

// A computed property for full name
const fullName = computed(() => {
  console.log('fullName computed re-evaluated'); // For demonstration
  return `${firstName.value} ${lastName.value}`;
});

// A computed property for total price
const totalPrice = computed(() => {
  console.log('totalPrice computed re-evaluated'); // For demonstration
  return quantity.value * unitPrice.value;
});

// Functions to update reactive sources
function updateFirstName(event) {
  firstName.value = event.target.value;
}

function updateLastName(event) {
  lastName.value = event.target.value;
}

function increaseQuantity() {
  quantity.value++;
}
</script>

<template>
  <div>
    <h2>Name Example</h2>
    <label>First Name: <input :value="firstName" @input="updateFirstName" /></label><br>
    <label>Last Name: <input :value="lastName" @input="updateLastName" /></label>
    <p>Full Name: {{ fullName }}</p>
  </div>

  <hr>

  <div>
    <h2>Price Example</h2>
    <p>Quantity: {{ quantity }}</p>
    <p>Unit Price: ${{ unitPrice.toFixed(2) }}</p>
    <button @click="increaseQuantity">Increase Quantity</button>
    <p>Total Price: ${{ totalPrice.toFixed(2) }}</p>
  </div>
</template>
How it works: This snippet demonstrates Vue 3's `computed` properties for deriving state efficiently. `computed` takes a getter function and returns a reactive ref. The key benefit is that `computed` values are cached based on their reactive dependencies. They will only re-evaluate when one of their dependencies (like `firstName`, `lastName`, `quantity`, or `unitPrice`) changes, preventing unnecessary recalculations and optimizing performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs