With Vue 3 (launched September 18, 2020), the Composition API introduces a new, flexible way to manage state and logic in your components. While the Options API is still supported, the Composition API encourages better separation of concerns, especially in large-scale applications.
Why Composition API?
The Composition API was introduced to address several challenges:
- Better logic reuse via composables
- More readable code in large components
- Full TypeScript support
Setup
Make sure your project uses Vue 3:
npm install vue@next
Basic Example
Here’s a simple counter using the Composition API:
<script setup>
import { ref } from 'vue'
const count = ref(0)
const increment = () => count.value++
</script>
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>
Core Concepts
ref()
: Makes a value reactivereactive()
: Makes an object reactivecomputed()
: Creates derived statewatch()
: Runs side-effects on changes
Composables
You can abstract logic into reusable functions:
// useCounter.js
import { ref } from 'vue'
export function useCounter() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
Use in your component:
<script setup>
import { useCounter } from './useCounter.js'
const { count, increment } = useCounter()
</script>
Lifecycle Hooks
Hooks like onMounted
, onUnmounted
, onUpdated
can be used within <script setup>
:
import { onMounted } from 'vue'
onMounted(() => {
console.log('Component mounted')
})
Migration Tips
- You can mix Options API and Composition API
- Start with isolated features
- Use
<script setup>
for brevity and simplicity
Vue 3’s Composition API offers a modern, scalable approach to writing components. If you’re building apps that need clean separation of logic or TypeScript support, Composition API is a must-learn. Try converting one of your existing components to Composition API to feel the difference.