cd ../blog
12 min read Vue

Vue 3 Composition API: Complete Mastery Guide

Learn to build powerful, reusable Vue components using the Composition API. From basics to advanced patterns that scale.

Vue Composition API Frontend
Vue 3 Composition API: Complete Mastery Guide

## The Composition API Revolution

Vue 3's Composition API transforms how we write components. It provides a more flexible, powerful way to organize component logic.

## Setup Function Basics

The setup function is where your Composition API logic lives:

vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const count = ref(0)

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

## Reactivity with ref() and reactive()

Create reactive state with two primary approaches:

javascript
import { ref, reactive } from 'vue'

// For primitive values and simple objects
const message = ref('Hello')
message.value = 'Updated'

// For complex objects
const user = reactive({
  name: 'Alice',
  email: 'alice@example.com',
  preferences: {
    theme: 'dark'
  }
})

// Direct mutation with reactive
user.name = 'Bob'
user.preferences.theme = 'light'

## Computed Properties

Derive reactive values from other reactive data:

javascript
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

const fullName = computed(() => {
  return `${firstName.value} ${lastName.value}`
})

// Computed with setter
const email = computed({
  get: () => user.email,
  set: (newEmail) => {
    user.email = newEmail
  }
})

## Lifecycle Hooks in Composition API

Access component lifecycle events:

javascript
import { onMounted, onUnmounted, onUpdated } from 'vue'

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

onUpdated(() => {
  console.log('Component updated!')
})

onUnmounted(() => {
  console.log('Cleanup before unmount')
})

## Extracting Reusable Logic with Composables

Extract logic into reusable functions:

javascript
// composables/useCounter.ts
import { ref, computed } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  const doubled = computed(() => count.value * 2)

  const increment = () => count.value++
  const decrement = () => count.value--
  const reset = () => count.value = initialValue

  return { count, doubled, increment, decrement, reset }
}

// Usage in component
const { count, doubled, increment } = useCounter(10)

## Real-World Example: Form Handling

javascript
import { reactive, computed } from 'vue'

function useForm(initialValues) {
  const form = reactive({ ...initialValues })
  const errors = reactive({})

  const isDirty = computed(() => {
    return Object.keys(form).some(key => form[key] !== initialValues[key])
  })

  const reset = () => {
    Object.assign(form, initialValues)
    Object.assign(errors, {})
  }

  const validate = () => {
    // validation logic
  }

  return { form, errors, isDirty, reset, validate }
}

## Conclusion

The Composition API unlocks a new level of code organization and reusability in Vue 3. Master it to write cleaner, more maintainable applications.

// Thanks for reading!