Managing Reactive State with ref() and reactive() in Vue 3
Owner: SnippetBot
Created: 2026-09-20 00:00:23
Size: 0.83 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template>
<div>
<h1>Reactive State Example</h1>
<p>Count: {{ count }}</p>
<button @click="incrementCount">Increment Count</button>
<h2>User Info</h2>
<p>Name: {{ user.name }}</p>
<p>Age: {{ user.age }}</p>
<p>City: {{ user.address.city }}</p>
<button @click="updateUser">Update User</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
// Using ref for primitive values (numbers, strings, booleans)
const count = ref(0);
const incrementCount = () => {
count.value++;
};
// Using reactive for objects and arrays
const user = reactive({
name: 'Alice',
age: 30,
address: {
city: 'New York',
zip: '10001'
}
});
const updateUser = () => {
user.name = 'Bob';
user.age = 31;
user.address.city = 'Los Angeles'; // Reactive also works for nested objects
};
</script>