JAVASCRIPT
Managing State with Vue 3 `ref` and `computed`
Learn to declare reactive state with `ref` and create efficient, cached derived values using `computed` properties in Vue 3 Composition API for dynamic UIs.
<script setup>
import { ref, computed } from 'vue';
// Declare a reactive variable using ref
const count = ref(0);
// A computed property that doubles the count
const doubledCount = computed(() => count.value * 2);
// Function to increment the count
const increment = () => {
count.value++;
};
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Doubled Count: {{ doubledCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
How it works: This snippet demonstrates the core reactivity system in Vue 3 using the Composition API. `ref` is used to declare a reactive primitive variable (`count`). `computed` is used to create a derived reactive property (`doubledCount`) that automatically updates whenever `count` changes, but only re-evaluates when its dependencies change, ensuring efficiency. The `increment` function modifies `count.value`, triggering updates in both the `count` display and `doubledCount`.