💚 Vue.js Beginner

What is the Composition API in Vue 3?

Why Interviewers Ask This

This is a classic screening question for Vue.js roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

The Composition API is a set of function-based APIs for writing Vue component logic, introduced in Vue 3 as an alternative to the Options API. It uses a setup() function (or <script setup> shorthand) where all reactive state, computed properties, watchers, and lifecycle hooks are defined using imported functions. Why Composition API? In the Options API, logic for one feature is split across data, methods, computed, watch, and lifecycle hooks. With Composition API, all logic for one feature lives together and can be extracted into a reusable composable function. script setup (recommended): <script setup> import { ref, computed, onMounted } from "vue"; const count = ref(0); const doubled = computed(() => count.value * 2); function increment() { count.value++; } onMounted(() => { console.log("Mounted"); }); </script>. Top-level bindings are automatically exposed to the template. Benefits: (1) Better TypeScript support (pure functions with types); (2) Logic reuse via composables (replace mixins); (3) Colocation of related logic; (4) Smaller production bundle (better tree-shaking). Comparison with Options API: both are fully supported; Options API is not deprecated. Choose Composition API for complex components, libraries, and TypeScript projects. Options API is fine for simple components and teams transitioning from Vue 2.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Vue.js experience.