The Composition API was created to make Vue components easier to organize and reuse. It helps manage complex logic by grouping related code together.
Why the Composition API exists in Vue
import { ref, computed } from 'vue'; export default { setup() { const count = ref(0); const double = computed(() => count.value * 2); function increment() { count.value++; } return { count, double, increment }; } }
The setup function is the main place to write logic in the Composition API.
Use ref to create reactive data, and computed for derived values.
ref.import { ref } from 'vue'; export default { setup() { const message = ref('Hello!'); return { message }; } }
computed to create a value based on reactive data.import { ref, computed } from 'vue'; export default { setup() { const count = ref(1); const squared = computed(() => count.value * count.value); return { count, squared }; } }
setup.import { ref } from 'vue'; export default { setup() { const isVisible = ref(true); function toggle() { isVisible.value = !isVisible.value; } return { isVisible, toggle }; } }
This Vue component uses the Composition API to manage a counter. The count is reactive, and double automatically updates when count changes. Clicking the button increases the count.
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
<button @click="increment">Add 1</button>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() {
count.value++;
}
</script>The Composition API helps keep related code close together, unlike the Options API which separates data, methods, and lifecycle hooks.
It works well with TypeScript because it uses plain JavaScript functions.
You can gradually adopt the Composition API in existing Vue projects.
The Composition API organizes component logic by grouping related code.
It makes code easier to read, reuse, and maintain.
It improves TypeScript support and flexibility in Vue apps.