π§© 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
| Feature | Options API | Composition API |
|---|---|---|
| Syntax | Object-based | Function-based (setup()) |
| Logic Organization | Split by option (data, methods, etc.) | Grouped by concern |
| Reusability | Mixins | Reusable functions (composables) |
| TypeScript Support | Limited | Excellent |
π§ͺ 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)makescountreactive.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()andreactive() - 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 andreactive()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 :
