The Composition API is a feature introduced in Vue.js 3 to provide a more flexible and powerful way to organize and reuse code logic in Vue components. It’s an alternative to the Options API, which is used in Vue 2.x.

With the Composition API, you can encapsulate and compose logic into reusable functions, making it easier to manage complex components. It encourages a more functional programming style and allows you to organize code based on logical concerns rather than lifecycle hooks.

Here’s a basic example of how you might use the Composition API in a Vue component:

In this example:

  • We import ref from Vue to create a reactive reference.
  • In the setup() function, we define the counter reactive state using ref().
  • We define an increment function that increments the counter.
  • Finally, we return the counter and increment function, which can be used in the template.

The Composition API provides more flexibility in how you organize your code, especially for larger and more complex components. It allows you to extract and reuse logic more easily, improving code maintainability and readability.

Here is the same component, with the exact same template, but using Composition API and <script setup> instead:

Leave a Reply

Your email address will not be published. Required fields are marked *