JAVASCRIPT

Creating Efficient Derived State with Vue 3 Computed Properties

Leverage Vue 3 computed properties to efficiently derive new state from existing reactive data, improving performance and code readability in your components.

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

const firstName = ref('John');
const lastName = ref('Doe');
const items = ref([
  { id: 1, name: 'Apple', category: 'Fruit', price: 1.00 },
  { id: 2, name: 'Banana', category: 'Fruit', price: 0.50 },
  { id: 3, name: 'Carrot', category: 'Vegetable', price: 0.75 },
  { id: 4, name: 'Milk', category: 'Dairy', price: 2.50 }
]);
const searchTerm = ref('');
const showFruitsOnly = ref(false);

// Computed property for full name
const fullName = computed(() => {
  return firstName.value + ' ' + lastName.value;
});

// Computed property for filtered and sorted items
const filteredItems = computed(() => {
  let result = items.value;

  if (searchTerm.value) {
    result = result.filter(item =>
      item.name.toLowerCase().includes(searchTerm.value.toLowerCase())
    );
  }

  if (showFruitsOnly.value) {
    result = result.filter(item => item.category === 'Fruit');
  }

  // Sort by name alphabetically
  return result.sort((a, b) => a.name.localeCompare(b.name));
});

// Computed property for total price of filtered items
const totalFilteredPrice = computed(() => {
  return filteredItems.value.reduce((sum, item) => sum + item.price, 0).toFixed(2);
});

function updateFirstName() {
  firstName.value = 'Jane';
}
</script>

<template>
  <div>
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
    <p>Full Name (Computed): {{ fullName }}</p>
    <button @click="updateFirstName">Change First Name</button>

    <hr />

    <h3>Item List</h3>
    <input type="text" v-model="searchTerm" placeholder="Search items..." />
    <label>
      <input type="checkbox" v-model="showFruitsOnly" /> Show Fruits Only
    </label>

    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }} ({{ item.category }}) - ${{ item.price.toFixed(2) }}
      </li>
    </ul>
    <p>Total Price of Filtered Items: ${{ totalFilteredPrice }}</p>
  </div>
</template>
How it works: Computed properties in Vue 3 allow you to define a piece of data that depends on other reactive data. They are automatically re-evaluated only when their reactive dependencies change, and their result is cached. This makes them highly efficient for complex transformations, filtering, or aggregations of data that might be displayed multiple times or used in other computations. They are read-only by default but can be made writable by providing both a `get` and `set` function.

Need help integrating this into your project?

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

Hire DigitalCodeLabs