In Vue.js, the Composition API is a new approach to organizing and reusing logic, introduced in Vue 3. Compared to the Options API, it offers greater flexibility, facilitating the extraction and reuse of functions, which is particularly beneficial for developing large or complex applications. The following sections provide a detailed explanation of how to define a component using the Composition API, along with a simple example.
Steps to Define Components Using Composition API:
-
Import Required APIs:
First, import the reactive APIs likerefandreactive, as well asdefineComponentand other required APIs from thevuepackage. -
Create the Component with
defineComponent:
Use thedefineComponentfunction to define the component, offering type inference and improved IDE integration. -
Set Up the
setupFunction:
Within the component, use thesetupfunction to define the component's logic. Thesetupfunction serves as the entry point for the Composition API, executing once when the component is created. Here, you can define reactive state, computed properties, and functions. -
Define Reactive State:
Usereforreactiveto define the component's reactive state.refis used for basic data types, whilereactiveis suitable for objects or complex data structures. -
Define Computed Properties and Watchers:
Usecomputedandwatchto define computed properties and watchers. -
Return Required Reactive Data and Methods:
Return all required reactive data and methods for the template at the end of thesetupfunction.
javascript<template> <div> <h1>{{ message }}</h1> <button @click="increment">Click me</button> <p>Count: {{ count }}</p> </div> </template> <script> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'CounterComponent', setup() { const count = ref(0); // Define reactive data const message = ref('Hello Vue 3 with Composition API!'); function increment() { count.value++; // Update reactive data } // Return all reactive data and methods needed for the template return { count, message, increment }; } }); </script>
In this example, we define a simple counter component. We use ref to create reactive count and message variables. We also define an increment method to increase the count value. All reactive data and methods are returned via the setup function, making them accessible and usable in the component's template.
Through this structure, the Composition API enables more modular and reusable component logic while maintaining code clarity and maintainability.