The Composition API is a set of Vue 3 functions that lets you write component logic using imports like ref, computed, and onMounted. Instead of splitting one feature across data, methods, and mounted options, you keep related code grouped together.
As components grow beyond a hundred lines, feature grouping makes reading and refactoring much easier. You can also extract any logical feature straight into a reusable composable function without mixin collisions.
flowchart TD
subgraph Options["Options API (Split by Option)"]
D["data()"]
M["methods"]
C["computed"]
end
subgraph Composition["Composition API (Grouped by Feature)"]
F1["Search Feature (ref, computed, watch)"]
F2["Auth Feature (ref, function, onMounted)"]
end
<script setup>this.In <script setup>, every top-level import, ref, and function is exposed directly to <template>.
<script setup>
import { ref, computed, onMounted } from 'vue';
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
onMounted(() => {
console.log('Composition API counter mounted');
});
</script>
<template>
<div class="comp-api-demo">
<h3>Composition API Counter</h3>
<p>Count: {{ count }} | Double: {{ doubleCount }}</p>
<button @click="increment">Add One</button>
</div>
</template>
setup() Return Objects with <script setup>: When using <script setup>, you do not write an explicit export default { setup() { return { ... } } } wrapper. Top-level bindings work automatically.<template> and <style scoped> blocks.await: Always call onMounted() or watch() synchronously before any await statement inside <script setup>.No, the Options API remains supported in Vue 3. However, <script setup> with the Composition API is the recommended default for new applications and large projects.
Yes. Both styles work side by side in the same Vue 3 project, so you can write new components in <script setup> without rewriting older files immediately.
ref need .value in JavaScript?Primitives like numbers and strings pass by value in JavaScript. Wrapping them in { value: 0 } lets Vue track reads and mutations reliably inside <script setup>.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.