Introduction to the Composition API
Understand what the Composition API is, the problem it solves, and how it compares to the Options API.
What Is the Composition API?
The Composition API is a set of function-based APIs — ref, reactive, computed, watch, lifecycle hooks — that let you write and organize a component's logic by feature or concern, rather than by splitting it across the Options API's fixed data/methods/computed blocks.
The Problem It Solves
In the Options API, a single feature's logic — say, a search box's state, its watcher, and its cleanup — gets scattered across separate data(), watch:, and lifecycle blocks. In a large component with many features, this makes it hard to see everything related to one feature at a glance. The Composition API lets you group all of one feature's logic together, in one place.
Because Composition API logic is just function calls, you can extract a reusable piece of stateful logic into its own function (a "composable") and reuse it across components — the subject of an upcoming lesson.
The setup() Function
Before <script setup> existed, Composition API logic lived inside an explicit setup() function, which returns everything the template needs access to. Understanding this form helps make sense of what <script setup> is a shorthand for.
<script>import { ref } from 'vue';
export default { setup() { const count = ref(0);
function increment() { count.value++; }
return { count, increment }; // exposed to the template },};</script>
<template> <button @click="increment">{{ count }}</button></template>Every earlier lesson in this course already used <script setup> — the modern, more concise syntax that compiles down to exactly this setup() pattern, without you needing to write the return statement yourself.
Options API Side by Side
The same counter, written the older way, for comparison — you'll see this style in existing Vue 2 and early Vue 3 codebases.
<script>export default { data() { return { count: 0 }; }, methods: { increment() { this.count++; }, },};</script>| Options API | Composition API | |
|---|---|---|
| Organization | By option type (data, methods, computed) | By logical feature/concern |
| this keyword | Used to access state and methods | Not needed — plain variables and functions |
| Reuse across components | Mixins (has downsides at scale) | Composables (plain functions) |
| TypeScript inference | Weaker | Strong, near-automatic |
FAQs
No — Vue 3 supports mixing them, though most teams pick one style consistently within a single project for clarity.
It scales better for complex components and large codebases, and has better TypeScript support — but the Options API remains a perfectly valid, simpler choice for small components.
Summary
The Composition API organizes logic by feature instead of by option type, and setup() (or its <script setup> shorthand) is where that logic lives. Next, you'll go deep on the two reactivity primitives you've been using throughout this course: ref() and reactive().