JAVASCRIPT

Using Computed Properties with computed in Vue 3

Create efficient, cached derived state using Vue 3's `computed` in Composition API. Automatically updates when dependencies change, optimizing performance.

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

const firstName = ref('John');
const lastName = ref('Doe');

// A simple computed property for full name
const fullName = computed(() => {
  return `${firstName.value} ${lastName.value}`;
});

const items = reactive([
  { id: 1, name: 'Laptop', price: 1200, quantity: 1 },
  { id: 2, name: 'Mouse', price: 25, quantity: 2 },
  { id: 3, name: 'Keyboard', price: 75, quantity: 1 }
]);

// A computed property for total price
const totalPrice = computed(() => {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
});

// A writable computed property
const userName = ref('Alice');
const greeting = computed({
  get() {
    return `Hello, ${userName.value}!`;
  },
  set(newValue) {
    userName.value = newValue.replace('Hello, ', '').replace('!', '');
  }
});

function changeFirstName() {
  firstName.value = 'Jane';
}

function updateMouseQuantity() {
  const mouse = items.find(item => item.name === 'Mouse');
  if (mouse) mouse.quantity++;
}
</script>

<template>
  <div>
    <h2>Full Name Example</h2>
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
    <p>Full Name: {{ fullName }}</p>
    <button @click="changeFirstName">Change First Name</button>

    <h2>Shopping Cart Total</h2>
    <ul>
      <li v-for="item in items" :key="item.id">
        {{ item.name }} - ${{ item.price }} x {{ item.quantity }}
      </li>
    </ul>
    <p>Total Price: ${{ totalPrice }}</p>
    <button @click="updateMouseQuantity">Add one more Mouse</button>

    <h2>Writable Computed Example</h2>
    <p>Greeting: {{ greeting }}</p>
    <button @click="greeting = 'Hello, Bob!'">Change Greeting to Bob</button>
    <p>Username (derived from writable computed): {{ userName }}</p>
  </div>
</template>
How it works: This snippet illustrates how to use `computed` properties in Vue 3's Composition API to create derived state that automatically updates when its reactive dependencies change. It demonstrates both a read-only computed property (like `fullName` and `totalPrice`) and a writable computed property using getter/setter functions, showing how to derive a value and also modify the underlying reactive state through the computed property.

Need help integrating this into your project?

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

Hire DigitalCodeLabs