JAVASCRIPT
Building a Reactive Counter with Vue 3 Composition API
Learn to build a simple reactive counter in Vue 3 using the Composition API, `ref` for reactive state, and `computed` properties for derived state in `script setup`.
<script setup>
import { ref, computed } from 'vue';
// Reactive state using ref
const count = ref(0);
// Computed property based on count
const doubleCount = computed(() => count.value * 2);
// Method to increment count
const increment = () => {
count.value++;
};
// Method to decrement count
const decrement = () => {
count.value--;
};
</script>
<template>
<div>
<h1>Counter: {{ count }}</h1>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<style scoped>
button {
margin: 5px;
padding: 10px 15px;
font-size: 16px;
cursor: pointer;
}
</style>
How it works: This snippet demonstrates the core of Vue 3's Composition API. We use `ref` to declare reactive state (`count`), allowing Vue to track changes and re-render the component. `computed` creates a reactive property (`doubleCount`) that automatically updates whenever its dependencies (`count`) change. Methods like `increment` and `decrement` directly modify the `ref` value, triggering reactivity. The `<script setup>` syntax simplifies component definition.