Vue.jsApril 12, 2026

Vue Composition API: Complete Guide

Learn how to use the Composition API to write more maintainable Vue applications.

Vue Composition API: Complete Guide

The Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options.

Why Composition API?

  1. Better logic reuse through composables
  2. More flexible code organization
  3. Better TypeScript integration
  4. Improved tree-shaking

Reactive State

vue
<script setup>
import { ref, reactive, computed } from 'vue'

// Primitive values
const count = ref(0)

// Objects
const user = reactive({
  name: 'Satish',
  role: 'Developer'
})

// Computed
const doubleCount = computed(() => count.value * 2)

function increment() {
  count.value++
}
</script>

Watchers

js
import { watch, watchEffect } from 'vue'

// Watch specific source
watch(count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`)
})

// Auto-track dependencies
watchEffect(() => {
  console.log(`Count is: ${count.value}`)
})

Lifecycle Hooks

js
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('Component mounted')
})

onUnmounted(() => {
  console.log('Component unmounted')
})