Understanding Vue Composition API

The Composition API is Vue 3's way of organizing component logic. Let's learn why it's awesome!

What's the Difference?

Options API (Old Way)

<script>
export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}
</script>

Composition API (New Way)

<script setup>
const count = ref(0)

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

Why Use Composition API?

1. Less Boilerplate

No more export default, data(), methods objects. Just write your logic directly!

2. Better TypeScript Support

Types work naturally without extra configuration.

3. Easier to Reuse Logic

You can extract logic into composables (reusable functions):

// composables/useCounter.js
export function useCounter() {
  const count = ref(0)
  
  function increment() {
    count.value++
  }
  
  return { count, increment }
}

Then use it anywhere:

<script setup>
const { count, increment } = useCounter()
</script>

Key Concepts

Reactive Data with ref

const message = ref('Hello')
message.value = 'World'  // Update the value

Computed Values

const doubled = computed(() => count.value * 2)

Lifecycle Hooks

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

Conclusion

The Composition API makes Vue code cleaner and more reusable. Once you get used to it, you'll never want to go back! 💪