Welcome to The Coding College! Vue Composition API is a feature introduced in Vue 3 to enhance code organization, reuse, and readability. It provides a flexible alternative to the traditional Options API, especially in large and complex applications.
In this guide, we’ll explore the Vue Composition API, its benefits, and how to use it effectively in your Vue applications.
What Is the Composition API?
The Composition API is a set of methods and lifecycle hooks that allow developers to organize and manage component logic more efficiently. It is particularly helpful for:
- Reusing logic across multiple components.
- Simplifying complex components by grouping related logic.
- Providing better TypeScript support.
Benefits of the Composition API
- Improved Logic Organization: Group related logic together instead of scattering it across different component options.
- Reusable Logic: Encapsulate logic in composable functions and reuse them across components.
- Better TypeScript Integration: Enhanced type inference and developer tooling.
- Future-Proof: Designed to work seamlessly with Vue’s evolving ecosystem.
Getting Started with the Composition API
To use the Composition API, you’ll rely on Vue’s setup
function, which is the entry point for Composition API logic.
Example: Counter Component
Here’s a simple counter example using the Composition API:
<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);
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
};
</script>
Key Points:
setup
Function: The primary function where Composition API logic is defined.- Reactive Variables: Use
ref
for reactive primitive values andreactive
for reactive objects.
Core Features of the Composition API
1. Reactive State with ref
and reactive
ref
: Creates a reactive value. Access the value with.value
.reactive
: Creates a reactive object.
Example: Using ref
and reactive
<script>
import { ref, reactive } from 'vue';
export default {
setup() {
const message = ref('Hello, Vue!');
const user = reactive({ name: 'John', age: 30 });
const updateMessage = () => {
message.value = 'Welcome to Vue 3!';
};
return {
message,
user,
updateMessage
};
}
};
</script>
2. Computed Properties
Computed properties can be created using the computed
function.
Example:
<script>
import { ref, computed } from 'vue';
export default {
setup() {
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
return {
firstName,
lastName,
fullName
};
}
};
</script>
3. Watchers
Use watch
and watchEffect
to react to changes in reactive data.
Example:
<script>
import { ref, watch } from 'vue';
export default {
setup() {
const count = ref(0);
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
return {
count
};
}
};
</script>
Composable Functions
Composable functions allow you to encapsulate and reuse logic across components.
Example: Creating a Composable Function
- Create a
useCounter.js
file:
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => {
count.value++;
};
return { count, increment };
}
- Use the composable function in a component:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { useCounter } from './useCounter';
export default {
setup() {
const { count, increment } = useCounter();
return {
count,
increment
};
}
};
</script>
Using Lifecycle Hooks
The Composition API provides lifecycle hooks such as onMounted
, onUpdated
, and onUnmounted
.
Example:
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const message = ref('Hello, World!');
onMounted(() => {
console.log('Component mounted');
});
onUnmounted(() => {
console.log('Component unmounted');
});
return {
message
};
}
};
</script>
Migrating from the Options API to the Composition API
Transitioning from the Options API to the Composition API can be done gradually. Both APIs can coexist in the same component.
Example: Mixing Options API and Composition API
<template>
<div>
<p>Message: {{ message }}</p>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
data() {
return {
oldMessage: 'Hello from Options API!'
};
},
setup() {
const message = ref('Hello from Composition API!');
return { message };
}
};
</script>
Best Practices for the Composition API
- Group Related Logic: Keep related logic in the same composable or
setup
block. - Use Descriptive Names: Make composable functions and variables self-explanatory.
- Keep It Modular: Encapsulate logic in reusable composable functions where possible.
- Avoid Overcomplicating: Use the Options API for simple components when Composition API isn’t necessary.
Conclusion
The Composition API is a powerful tool for organizing and reusing logic in Vue applications. By leveraging setup
, reactive variables, and composable functions, you can build scalable and maintainable applications with ease.
For more in-depth tutorials and tips on Vue and other web development topics, visit The Coding College.