JAVASCRIPT
Managing Reactive State with ref and computed in Vue 3
Learn to manage reactive data in Vue 3 using `ref` for primitive types and `computed` properties for derived, automatically updating values. Essential for dynamic UIs.
import { ref, computed } from 'vue';
export default {
setup() {
const count = ref(0);
const doubledCount = computed(() => count.value * 2);
const increment = () => {
count.value++;
};
return {
count,
doubledCount,
increment
};
}
};
How it works: This snippet demonstrates fundamental reactivity in Vue 3. `ref` is used to create a reactive reference for a primitive value (like a number), allowing Vue to track its changes. `computed` creates a reactive property that automatically re-evaluates its value whenever its reactive dependencies (in this case, `count.value`) change. This is efficient as it's cached until dependencies change. The `increment` method modifies the `count` ref, which in turn updates `doubledCount` and triggers UI re-renders where they are used.