JAVASCRIPT
Managing Reactive State with ref and reactive
Learn to manage reactive data in Vue 3 using `ref` for primitive values and `reactive` for objects, ensuring your UI updates efficiently and predictably.
import { ref, reactive, onMounted } from 'vue';
export default {
setup() {
// Reactive primitive with ref
const count = ref(0);
// Reactive object with reactive
const user = reactive({
name: 'Alice',
age: 30
});
const increment = () => {
count.value++; // Access value with .value for ref
};
const changeName = () => {
user.name = 'Bob'; // Direct mutation for reactive object
};
onMounted(() => {
console.log(`Initial count: ${count.value}`);
console.log(`Initial user: ${user.name}`);
});
return {
count,
user,
increment,
changeName
};
}
};
/*
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment Count</button>
<p>User Name: {{ user.name }}</p>
<p>User Age: {{ user.age }}</p>
<button @click="changeName">Change User Name</button>
</div>
</template>
*/
How it works: This snippet demonstrates Vue 3's core reactivity system using `ref` and `reactive`. `ref` is used for creating reactive primitive values (like numbers, strings, booleans), requiring access via `.value`. `reactive` is used for making objects reactive, allowing direct property access and modification. Both ensure that changes automatically trigger UI updates, and are fundamental for state management in Vue's Composition API.