JAVASCRIPT
Managing Reactive State with Vue 3 Composition API
Learn to manage component-level reactive state in Vue 3 using `ref` for primitives and `reactive` for objects, updating UI efficiently.
<script setup>
import { ref, reactive } from 'vue';
// Using ref for primitive values (numbers, strings, booleans)
const count = ref(0);
function increment() {
count.value++; // .value is needed to access/modify ref inside <script setup>
}
// Using reactive for objects (plain objects, arrays, Maps, Sets)
const user = reactive({
firstName: 'John',
lastName: 'Doe',
age: 30
});
function celebrateBirthday() {
user.age++; // Direct access for reactive properties
}
</script>
<template>
<div>
<h2>Ref Example: Counter</h2>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
<div>
<h2>Reactive Example: User Profile</h2>
<p>Name: {{ user.firstName }} {{ user.lastName }}</p>
<p>Age: {{ user.age }}</p>
<button @click="celebrateBirthday">Happy Birthday!</button>
</div>
</template>
How it works: This snippet demonstrates how to manage reactive state in Vue 3 using the Composition API. `ref` is used for primitive values like numbers, strings, or booleans, requiring `.value` to access or modify them within the `<script setup>` block. `reactive` is used for objects (including arrays), allowing direct access to its properties without `.value`. Both methods ensure that when the state changes, the UI automatically updates.