Vue.js is a popular JavaScript framework used for building interactive user interfaces and single-page applications. With the release of Vue 3, the Composition API was introduced as a powerful new way to organize and reuse code within Vue components. This chapter will explore the Composition API in detail, starting from the basics and moving towards advanced concepts. By the end of this chapter, you will have a thorough understanding of how to use the Composition API effectively in your Vue.js projects.
The Composition API is a set of additive, function-based APIs that allow you to compose component logic in a more flexible and readable way compared to the Options API. It is inspired by React’s Hooks and enables better code organization, reuse, and type inference
The Composition API offers several advantages over the traditional Options API:
It allows you to group related code by feature rather than by lifecycle hook, making your components more readable and maintainable.
Logic can be easily extracted into reusable functions, known as composables, which can be shared across different components.
With TypeScript, the Composition API provides better type inference and autocompletion, leading to fewer runtime errors.
Before using the Composition API, ensure you have Vue 3 installed. If you are starting a new project, you can create a Vue 3 project using Vue CLI.
First, install Vue CLI if you haven’t already:
npm install -g @vue/cli
Then, create a new Vue 3 project:
vue create my-vue3-project
cd my-vue3-project
Select the default Vue 3 preset or manually choose Vue 3 features.
The setup
function is the entry point for using the Composition API in a component. It is called before any lifecycle hooks and serves as a place to declare reactive state, computed properties, and methods.
{{ message }}
ref
function is used to create a reactive reference.setup
function returns an object that exposes the reactive properties to the template.The ref
and reactive
functions are used to create reactive state.
ref
{{ count }}
ref
creates a reactive reference. To access or modify its value, use count.value
.reactive
{{ state.count }}
reactive
creates a reactive object. Access properties directly from the object, e.g., state.count
.Computed properties are derived state that depends on other reactive state. Use the computed
function to create them.
{{ doubleCount }}
computed
function takes a getter function and returns a reactive computed property.Watchers allow you to perform side effects in response to reactive state changes. Use the watch
function to create watchers.
{{ count }}
watch
takes two arguments: the reactive source to watch and a callback function that runs when the source changes.The Composition API provides equivalents for all the Options API lifecycle hooks. These hooks can be used inside the setup
function.
{{ message }}
onMounted
and onUnmounted
are used to register code that runs when the component is mounted and unmounted, respectively.The provide
and inject
functions allow you to pass data from a parent component to its descendants, similar to dependency injection.
// ParentComponent.vue
// ChildComponent.vue
{{ message }}
provide
makes a value available to all descendants.inject
is used to access the provided value in a descendant component.Custom composables are reusable functions that encapsulate state and logic. They follow a similar pattern to Vue components but can be used across multiple components.
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => {
count.value++;
};
return {
count,
increment,
};
}
// CounterComponent.vue
{{ count }}
useCounter
is a custom composable that provides a counter state and increment function.Let’s create a form component that uses the Composition API to manage form state and validation.
ref
is used to create reactive form fields.computed
properties are used for validation.Let’s create a component that fetches data from an API using the Composition API.
Loading...
{{ error }}
{{ data }}
ref
is used to create reactive state for data
, loading
, and error
.onMounted
is used to fetch data when the component mounts.The Composition API in Vue.js provides a flexible and powerful way to organize and reuse component logic. By mastering the basic and advanced concepts of the Composition API, you can create more maintainable and scalable Vue applications. Happy coding !❤️