💚 Vue.js Beginner

What is the Composition API in Vue 3?

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.