Sobes.tech
Middle

What is Composition API in Vue 3? How does it differ from Options API?

sobes.tech AI

Answer from AI

The Composition API in Vue 3 is a new way to organize and reuse component logic based on functions that return reactive states and methods. Unlike the Options API, where logic is divided into options (data, methods, computed, etc.), the Composition API groups related logic together, improving code readability and scalability.

Main differences:

  • Logic grouping: The Composition API allows combining related logic into functions (composition functions) rather than splitting it into options.
  • Better reusability: Logic can be easily extracted and reused across components.
  • More explicit reactive management: Uses functions like ref, reactive, computed to create reactive data.

Example of using the Composition API:

import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const double = computed(() => count.value * 2);

    function increment() {
      count.value++;
    }

    return { count, double, increment };
  }
}