Chapter 5. Composition API

In the previous chapter, you learned how to compose Vue components using the classic Options API. Despite it being the most common API for composing Vue components since Vue 2, using Options API can lead to unnecessary code complexity, unreadability for large component code, and logic reusability between them. For such use cases, this chapter introduces an alternative approach for composing Vue components, the Composition API.

In this chapter, we will explore the different composition hooks to create a functional stateful element in Vue. We also will learn how to combine Options API and Composition API for better reactive control and to compose our own reusable composable for our application.

Setting Up Components with Composition API

Composing components using the Options API is a common practice in Vue. However, in many cases, we want to reuse part of the component logic without worrying about the overlapping data and methods like in mixins1, or a component that is more readable and organized. Composition API can be helpful in such scenarios.

Introduced in Vue 3.0, Composition API provides an alternative way to compose stateful and reactive components with the help of the setup() hook (“setup”) or <script setup> tag. The setup() hook is part of the component’s options object and runs once before initializing and creating the component instance (before beforeCreate() hook).

You can only use Composition API functions or composables (“Creating Your Reusable ...

Get Learning Vue now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.