How to Use Composition Api in Vue
Introduction The Composition API in Vue.js represents a significant evolution in the way developers build and organize components. Introduced in Vue 3, the Composition API offers a more flexible and scalable approach to managing component logic compared to the traditional Options API. This tutorial will guide you through understanding what the Composition API is, its importance in modern Vue devel
Introduction
The Composition API in Vue.js represents a significant evolution in the way developers build and organize components. Introduced in Vue 3, the Composition API offers a more flexible and scalable approach to managing component logic compared to the traditional Options API. This tutorial will guide you through understanding what the Composition API is, its importance in modern Vue development, and how to effectively use it to build maintainable, readable, and reusable code.
By the end of this tutorial, you'll have a comprehensive understanding of the Composition APIs syntax, practical implementation, best practices, useful tools, and real-world examples. Whether you are new to Vue or looking to modernize your existing projects, mastering the Composition API is essential to harnessing the full power of Vue 3.
Step-by-Step Guide
1. Understanding the Basics of Composition API
The Composition API allows you to organize component logic by function rather than by lifecycle hooks or component options. Instead of separating concerns by the Options APIs data, methods, and computed properties, you group related logic together using functions such as setup(), ref(), and reactive().
2. Setting Up a Vue 3 Project
Before diving into the Composition API, ensure you have Vue 3 installed. You can create a new project using Vue CLI or Vite with the following command:
Using Vue CLI:
vue create my-vue3-app
Using Vite:
npm create vite@latest my-vue3-app -- --template vue
Once your project is ready, navigate into your project folder and start the development server.
3. Using the setup() Function
The setup() function is the entry point for Composition API logic inside a Vue component. It runs before the component is created and serves as the place to declare reactive state, computed properties, and functions.
Example:
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment
};
}
};
4. Declaring Reactive State with ref() and reactive()
To create reactive state, Vue provides two main APIs:
- ref(): Used for primitive values like numbers, strings, or booleans.
- reactive(): Used for objects and arrays to create deeply reactive state.
Example with ref():
const message = ref('Hello World');
Example with reactive():
const user = reactive({
name: 'John Doe',
age: 30
});
5. Creating Computed Properties
Computed properties are derived state based on reactive data. With the Composition API, you use the computed() function to declare them.
import { ref, computed } from 'vue';
const count = ref(5);
const doubleCount = computed(() => count.value * 2);
6. Using Lifecycle Hooks within setup()
Vue 3 exposes lifecycle hooks as functions that you can import and use inside setup(). For example, to run code when the component is mounted, import and use onMounted():
import { onMounted } from 'vue';
onMounted(() => {
console.log('Component mounted!');
});
7. Organizing Logic with Composables
Composables are reusable functions that encapsulate Composition API logic, allowing you to share functionality across components.
Example of a composable that manages a counter:
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment
};
}
Use the composable inside any components setup():
import { useCounter } from './useCounter';
export default {
setup() {
const { count, increment } = useCounter();
return { count, increment };
}
};
Best Practices
1. Group Related Logic Together
Instead of scattering reactive state and functions across the component, group them by feature or purpose. This makes your code more readable and maintainable.
2. Use Composables for Reusability
Extract common logic into composables to avoid duplication and improve testability across your app.
3. Return Only Necessary State and Methods
Inside setup(), return only what the template or other parts of your component need. Avoid returning unnecessary internals.
4. Prefer ref() for Primitives and reactive() for Objects
This distinction helps keep your state management predictable and performant.
5. Use TypeScript for Better Type Safety
If your project supports TypeScript, leverage it to catch errors early and improve developer experience when using the Composition API.
6. Avoid Overusing setup()
While powerful, keep the setup() function focused. For very large components, consider splitting logic into multiple composables.
Tools and Resources
1. Official Vue 3 Documentation
The Vue.js official docs provide comprehensive guides and API references for the Composition API: https://vuejs.org/guide/extras/composition-api-faq.html
2. Vue Devtools
Vue Devtools extension supports Vue 3 and Composition API debugging, making it easier to inspect reactive state and component structure.
3. Volar (VS Code Extension)
For TypeScript users, Volar offers excellent Composition API support, including type inference and auto-completion.
4. VueUse Library
VueUse is a collection of well-maintained composables that can speed up your development.
5. Code Playground
Use tools like CodeSandbox or StackBlitz to experiment with Composition API code live.
Real Examples
Example 1: Simple Counter Component
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
}
};
</script>
Example 2: Fetch Data with Lifecycle Hook
<template>
<div>
<h2>User Data</h2>
<div v-if="loading">Loading...</div>
<div v-else>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
</div>
</div>
</template>
<script>
import { reactive, onMounted } from 'vue';
export default {
setup() {
const user = reactive({ name: '', email: '' });
const loading = ref(true);
onMounted(async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
user.name = data.name;
user.email = data.email;
loading.value = false;
});
return { user, loading };
}
};
</script>
Example 3: Using a Composable for Form Validation
// useFormValidation.js
import { ref } from 'vue';
export function useFormValidation() {
const errors = ref({});
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(email)) {
errors.value.email = 'Invalid email address';
} else {
delete errors.value.email;
}
}
return { errors, validateEmail };
}
<template>
<form @submit.prevent="submitForm">
<input v-model="email" @input="validateEmail(email)" placeholder="Email" />
<span v-if="errors.email">{{ errors.email }}</span>
<button type="submit">Submit</button>
</form>
</template>
<script>
import { ref } from 'vue';
import { useFormValidation } from './useFormValidation';
export default {
setup() {
const email = ref('');
const { errors, validateEmail } = useFormValidation();
function submitForm() {
validateEmail(email.value);
if (Object.keys(errors.value).length === 0) {
alert('Form submitted!');
}
}
return { email, errors, validateEmail, submitForm };
}
};
</script>
FAQs
What is the main advantage of using Composition API over Options API?
The Composition API provides better logic organization, reusability, and type inference, especially in complex components. It improves code readability by grouping related logic together rather than scattering it across lifecycle hooks and options.
Can I use Composition API with existing Vue 2 projects?
Vue 2 does not natively support the Composition API, but you can use it with Vue 2.7 or later, which backports some Composition API features. For full support, upgrading to Vue 3 is recommended.
Is the Composition API harder to learn than the Options API?
Initially, the Composition API may seem more complex due to its functional approach, but with practice, it becomes easier to understand and offers more powerful patterns for large-scale applications.
Do I need to rewrite all my components to use the Composition API?
No. The Composition API is fully compatible with the Options API, allowing you to incrementally adopt it in your existing projects.
How do I debug reactive state created with ref() or reactive()?
Use Vue Devtools, which supports inspection of reactive variables in Vue 3 components and helps visualize reactivity and component trees.
Conclusion
The Vue Composition API is a powerful tool that enhances the way developers write and manage component logic. By shifting from the traditional Options API to the Composition API, you gain flexibility, better organization, and improved code reuse, especially in complex applications. This tutorial covered the fundamentals, practical steps, best practices, and useful resources to get you started with the Composition API confidently.
Embracing the Composition API will future-proof your Vue projects and enable you to build scalable, maintainable, and efficient applications. Begin experimenting with setup(), ref(), reactive(), and composables today to unlock Vue 3s full potential.