Blog/Understanding Vue 3 Composition API: A Practical Guide

Understanding Vue 3 Composition API: A Practical Guide

The Composition API is one of the most significant features introduced in Vue 3. It provides a more flexible and powerful way to organize component logic, especially for complex components. Unlike the Options API, it allows you to group related code together, making your components more readable and maintainable.

Basic Setup with ref and reactive

The two main ways to create reactive state in the Composition API are ref() for primitive values and reactive() for objects:

import { ref, reactive } from 'vue'

export default {
  setup() {
    // ref for primitives
    const count = ref(0)

    // reactive for objects
    const user = reactive({
      name: 'Juan',
      email: 'juan@example.com'
    })

    function increment() {
      count.value++ // Note: .value is needed for ref
    }

    return { count, user, increment }
  }
}

Composables: Reusable Logic

One of the biggest advantages of the Composition API is the ability to extract and reuse logic across components using composables:

// useCounter.js
import { ref } from 'vue'

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

  function increment() {
    count.value++
  }

  function decrement() {
    count.value--
  }

  return { count, increment, decrement }
}

// In your component
import { useCounter } from './useCounter'

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

Conclusion

The Composition API gives you more control over how you structure your component logic. It's particularly useful when building large applications where code organization and reusability are critical. Start small by converting a few components and you'll quickly see the benefits.