JAVASCRIPT

Managing Reactive State and Computed Properties in Vue 3

Learn to efficiently manage reactive data and derive computed values using Vue 3's Composition API, `ref` and `computed`, for dynamic component logic.

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

// Reactive primitive state with ref
const count = ref(0);

// Reactive object state (ref automatically unwraps nested refs)
const user = ref({
  firstName: 'John',
  lastName: 'Doe'
});

// Computed property: automatically re-evaluates when dependencies change
const fullName = computed(() => {
  return `${user.value.firstName} ${user.value.lastName}`;
});

const increment = () => {
  count.value++;
};

const changeName = () => {
  user.value.firstName = 'Jane';
  user.value.lastName = 'Smith';
};
</script>

<template>
  <div>
    <h2>Counter</h2>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>

    <h2>User Info</h2>
    <p>First Name: {{ user.firstName }}</p>
    <p>Last Name: {{ user.lastName }}</p>
    <p>Full Name (Computed): {{ fullName }}</p>
    <button @click="changeName">Change User Name</button>
  </div>
</template>
How it works: This snippet demonstrates fundamental reactivity in Vue 3's Composition API. `ref` is used to create reactive references for both primitive values (like `count`) and objects (like `user`). To access or modify the value of a `ref` within JavaScript, you must use `.value`. However, within the template, Vue automatically unwraps `ref`s, so you can access `count` directly. `computed` is used to create a reactive property (`fullName`) that automatically re-evaluates its value only when its dependencies (`user.firstName`, `user.lastName`) change, ensuring efficiency by caching the result.

Need help integrating this into your project?

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

Hire DigitalCodeLabs