0
0
Vueframework~5 mins

Why the Composition API exists in Vue

Choose your learning style9 modes available
Introduction

The Composition API was created to make Vue components easier to organize and reuse. It helps manage complex logic by grouping related code together.

When your component has many features and you want to keep code clean and organized.
When you want to reuse logic across multiple components easily.
When you need better TypeScript support in your Vue app.
When you want to improve readability by grouping related code together.
When you want more flexibility than the Options API offers.
Syntax
Vue
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 };
  }
}

The setup function is the main place to write logic in the Composition API.

Use ref to create reactive data, and computed for derived values.

Examples
Simple reactive data example using ref.
Vue
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('Hello!');
    return { message };
  }
}
Using computed to create a value based on reactive data.
Vue
import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(1);
    const squared = computed(() => count.value * count.value);
    return { count, squared };
  }
}
Adding a function to change reactive state inside setup.
Vue
import { ref } from 'vue';

export default {
  setup() {
    const isVisible = ref(true);
    function toggle() {
      isVisible.value = !isVisible.value;
    }
    return { isVisible, toggle };
  }
}
Sample Program

This Vue component uses the Composition API to manage a counter. The count is reactive, and double automatically updates when count changes. Clicking the button increases the count.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double: {{ double }}</p>
    <button @click="increment">Add 1</button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const count = ref(0);
const double = computed(() => count.value * 2);

function increment() {
  count.value++;
}
</script>
OutputSuccess
Important Notes

The Composition API helps keep related code close together, unlike the Options API which separates data, methods, and lifecycle hooks.

It works well with TypeScript because it uses plain JavaScript functions.

You can gradually adopt the Composition API in existing Vue projects.

Summary

The Composition API organizes component logic by grouping related code.

It makes code easier to read, reuse, and maintain.

It improves TypeScript support and flexibility in Vue apps.