Vue: Options API vs. Composition API
Options API organizes Vue components by property type (data, methods). Composition API organizes them by logical feature. Use Composition API for complex components with tangled logic or for creating reusable 'composable' functions.
WHY IT EXISTS: In large Vue components, related pieces of logic—like fetching data, handling loading states, and managing errors—often become scattered across different sections of the component's options (data, methods, mounted). The Composition API was created to solve this by allowing developers to group code by logical concern, not by option type, and to enable clean, powerful logic reuse.
THE MENTAL MODEL: Think of it as organizing a filing cabinet. The Options API is like organizing by document type: one drawer for all invoices, one for all contracts, one for all memos. The Composition API is like organizing by project: one folder contains the invoice, contract, and memos for 'Project Alpha', making it easy to see everything related to that single concern.
HOW IT WORKS: The Options API uses a single exported object with properties like data, methods, and computed. Vue reads this structure to build the component. The Composition API uses a setup function (or <script setup>) where you import and use functions like ref() for reactive state, onMounted() for lifecycle hooks, and watch() for watchers. This allows you to declare and group these reactive parts anywhere within setup, typically by feature.
WHEN TO USE IT: Use the Composition API for complex components, when you need to extract and reuse stateful logic across multiple components (via 'composables' like useFetch), or when you need better TypeScript inference. Use the Options API for simpler components, when teaching Vue to beginners, or when a component's logic is self-contained and straightforward.
WHEN NOT TO USE IT: Using the Composition API can be overkill for simple, presentational components where its organizational benefits are negligible. The Options API becomes a liability in large components where tracking a single feature requires jumping between the data, methods, and watch sections, making the code harder to reason about and refactor.
ONE CANONICAL EXAMPLE: Imagine a feature for fetching user data. With the Options API, user, isLoading, and error would be in the data object, the fetchUser function in methods, and the call to it in the mounted hook. The logic is fragmented. With the Composition API, you can create a useUser composable that groups the user ref, isLoading ref, error ref, and the fetchUser function all in one place. The component then simply calls const { user, isLoading, error } = useUser() to get all the related logic, which is now co-located and reusable.
Read the original → vuejs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.