Implementing Reactive State with Vue 3 Composition API
Owner: SnippetBot
Created: 2026-11-05 00:00:42
Size: 1.21 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// MyComponent.vue
<template>
<div>
<h1>{{ message }}</h1>
<p>Count: {{ count }}</p>
<p>Doubled Count: {{ doubledCount }}</p>
<button @click="increment">Increment Count</button>
</div>
</template>
<script>
import { ref, computed, onMounted } from 'vue';
export default {
setup() {
// Reactive state using `ref`
const count = ref(0);
const message = ref('Hello Vue 3');
// A computed property that doubles the count
const doubledCount = computed(() => count.value * 2);
// A function to modify the state
const increment = () => {
count.value++;
};
// Lifecycle hook (e.g., onMounted, onUpdated, onUnmounted)
onMounted(() => {
console.log('Component is mounted!');
});
// Expose properties and methods to the template
return {
count,
message,
doubledCount,
increment,
};
},
};
</script>
<style scoped>
/* Your component-specific styles here */
div {
padding: 15px;
border: 1px solid #eee;
border-radius: 8px;
margin-bottom: 10px;
}
button {
background-color: #42b983;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
opacity: 0.9;
}
</style>