Vue Reactivity System
Estimated reading: 4 minutes 303 views

Vue Composition API – Organize and Scale Vue Apps Efficiently (2025 Guide)


Introduction – What Is the Vue Composition API?

The Vue Composition API is a powerful feature introduced in Vue 3 that provides an alternative, more flexible syntax for organizing component logic. It enhances code reusability, simplifies TypeScript integration, and improves component scalability—especially in large applications.

In this guide, you’ll learn:

  • What the Composition API is and why it exists
  • Key features: setup(), ref(), reactive(), watch(), computed()
  • Real-world use cases and examples
  • Best practices and common mistakes to avoid

Why Use the Composition API?

While the Options API (used in Vue 2) is beginner-friendly, it can lead to scattered logic in large components. Composition API solves this by grouping logic by feature instead of by option type (data, methods, computed, etc.).


Composition API vs Options API

FeatureOptions APIComposition API
SyntaxObject-basedFunction-based (setup())
Logic OrganizationSplit by option (data, methods, etc.)Grouped by concern
ReusabilityMixinsReusable functions (composables)
TypeScript SupportLimitedExcellent

Basic Example – setup() Function

<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

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

export default {
  setup() {
    const count = ref(0);
    const increment = () => count.value++;

    return { count, increment };
  }
}
</script>

Explanation:

  • ref(0) makes count reactive.
  • setup() runs before the component is created.
  • Values returned from setup() are exposed to the template.

ref() vs reactive()

ref() – For primitives:

const name = ref('Vue');
console.log(name.value); // 'Vue'

reactive() – For objects:

const user = reactive({ name: 'Vue', age: 3 });
console.log(user.name); // 'Vue'

Computed Properties with Composition API

import { computed } from 'vue';

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

double updates automatically when count changes.


Watchers in Composition API

import { watch } from 'vue';

watch(count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`);
});

Use watchers for side effects like API calls, local storage updates, or debouncing.


Real-World Example – Login Form with Validation

<template>
  <form @submit.prevent="submit">
    <input v-model="email" placeholder="Email" />
    <input v-model="password" type="password" placeholder="Password" />
    <button>Login</button>
  </form>
</template>

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

export default {
  setup() {
    const email = ref('');
    const password = ref('');

    const submit = () => {
      if (email.value && password.value) {
        alert(`Logged in as ${email.value}`);
      } else {
        alert('Please fill in all fields');
      }
    };

    return { email, password, submit };
  }
}
</script>

Creating Reusable Logic – Composables

Composables are reusable functions that use Composition API features.

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

export function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  return { count, increment };
}

Usage:

import { useCounter } from './useCounter';

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

Structure of setup()

Inside setup() you can:

  • Access reactive data with ref() and reactive()
  • Return data to use in the template
  • Use lifecycle hooks like onMounted()
  • Create computed properties and watchers
  • Call composables

🚨 Common Mistakes with Composition API

Forgetting .value on ref()
Always use .value to access or update ref values.

Returning nothing from setup()
Must return reactive variables and functions for template use.

Using options like data() or methods inside setup()
Use Composition API methods instead.


Summary – Recap & Next Steps

The Vue Composition API brings modular, scalable, and TypeScript-friendly design to Vue 3. By organizing logic by concern and enabling reusable hooks, it promotes cleaner and more maintainable components.

Key Takeaways:

  • Use setup() to define logic in Vue 3 components
  • Use ref() for primitives and reactive() for objects
  • Return reactive data/functions to make them available in templates
  • Create reusable composables to share logic across components

Real-World Relevance:
Ideal for complex components, large projects, and teams needing reusable, testable logic.


FAQ Section

What is the Composition API in Vue?

It’s a function-based syntax that organizes component logic using setup(), providing better scalability and reuse.


What is ref() used for?

ref() is used to create reactive primitive values like numbers, strings, and booleans.


How is reactive() different from ref()?

reactive() is for objects and arrays, while ref() is for single primitive values.


Can I use both Options API and Composition API?

Yes, Vue 3 supports mixing both, but it’s best to stick to one for consistency.


Why is Composition API better for TypeScript?

Because it uses function-based logic and explicit typing, making it more predictable and easier to type-check.


Share Now :
Share

Vue Composition API

Or Copy Link

CONTENTS
Scroll to Top