Skip to content

What Is the Vue Composition API?

The Vue Composition API, introduced in Vue 3.0, gives developers a better way to organise and share component logic. In Vue 2 logic was usually split across the Options API's data, methods and other options; the Composition API offers a more flexible, readable and organised alternative.

Its main characteristics are:

  1. Organising logic with functions: the Composition API encourages splitting component logic into reusable functions (composables). State management and behaviour can be grouped by feature instead of by option type.
  2. Vue's reactivity system: it builds on Vue's reactivity, with ref and reactive making state management simple.
  3. The setup function: the Composition API is based on the setup function introduced in Vue 3. It runs while the component is being created and prepares its reactive state, methods and everything else the template needs.

An example:

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

<script>
import { ref } from 'vue';

export default {
  setup() {
    // Declare reactive state
    const count = ref(0);

    // Declare behaviour
    function increment() {
      count.value++;
    }

    // Expose them to the template
    return {
      count,
      increment,
    };
  },
};
</script>

Here the Composition API manages a counter's state and its increment function. setup runs when the component starts and configures it by returning the reactive state and functions.

Have a question about this article? Write to me