Monday, April 6, 2026

Vue | Composition API

The Composition API is a modern way to write Vue components (introduced in Vue 3) where you organize code by logic/functionality instead of by options.


Simple Definition

Composition API lets you group related logic together using functions, making code more reusable and cleaner.


Options API vs Composition API

Options API (old way)
export default {
data() {
return { count: 0 }
},
methods: {
increment() {
this.count++
}
}
}

Composition API (new way)
import { ref } from 'vue'

export default {
setup() {
const count = ref(0)

function increment() {
count.value++
}

return { count, increment }
}
}

Key Features

1. setup() function
  • Entry point of Composition API
  • Runs before component is created

2. ref() (reactive primitive values)
ref is for single values, can be used with numbers, boolean, string and even objects.
const count = ref(0)

Access with .value: count.value


3. reactive() (for objects)
import { reactive } from 'vue'
reactive is for Objects
  • Used for objects (including arrays)
  • Makes the whole object reactive
Makes the whole object reactive


const state = reactive({ count: 0, name: 'John' })

Direct access

4. Lifecycle hooks

Can be used in setup
import { onMounted } from 'vue'

export default {
setup() {
onMounted(() => {
console.log('mounted')
})
            }
                        }

Why Composition API?

  • Better code organization
    Group related logic together
  • Reusability
    Create reusable functions (called composables)
  • Cleaner for large apps
    Avoid messy large components

Example (Reusable Logic)
// useCounter.js
import { ref } from 'vue'

export function useCounter() {
const count = ref(0)

function increment() {
count.value++
}

return { count, increment }
}
// Component
import { useCounter } from './useCounter'

export default {
setup() {
const { count, increment } = useCounter()
return { count, increment }
}
}

Mental Model
  • Options API → organize by type (data, methods, etc.)
  • Composition API → organize by feature/logic

Easy Analogy
  • Options API = different folders 📁 (data, methods…)
  • Composition API = feature-based grouping 

When to Use It?

✔ Large applications
✔ Reusable logic
✔ Vue 3 projects

Small/simple components (Options API is fine)


Summary
Composition API = flexible, reusable, and cleaner way to write Vue 3 components

No comments:

Post a Comment

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...