JAVASCRIPT
Vue 3 Composition API with script setup
Learn to use Vue 3's Composition API with `script setup` for reactive state (`ref`), computed properties, watchers, and lifecycle hooks (`onMounted`) in a concise way.
<template>
<div>
<h1>Counter: {{ count }}</h1>
<h2>Double Count: {{ doubleCount }}</h2>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref, computed, watch, onMounted } from 'vue';
// Reactive state
const count = ref(0);
// Computed property
const doubleCount = computed(() => count.value * 2);
// Method to update state
const increment = () => {
count.value++;
};
// Watcher
watch(count, (newCount, oldCount) => {
console.log(`Count changed from ${oldCount} to ${newCount}`);
});
// Lifecycle hook
onMounted(() => {
console.log('Component is mounted!');
});
</script>
How it works: This snippet demonstrates the core features of Vue 3's Composition API within a `<script setup>` block. It uses `ref` to declare a reactive state variable `count`, `computed` to create a derived property `doubleCount` that automatically updates when `count` changes, and a `watch` function to react to changes in `count`. The `onMounted` lifecycle hook executes code once the component has been mounted to the DOM, making development more intuitive and organized.