The Composition API is a great way to share application logic between components in Vue.js. Not only can you organize repetitive snippets of code into separate files, you can also make them easily reusable.
The Composition API allows you to keep your variables reactive in shared snippets of code, which can be a huge improvement over implementations built in previous versions of Vue, even for enterprise-sized applications. According to official documentation, the deployment of the Composition API was necessary because efficient code sharing between components was a problem in larger applications.
Although there has been a solution to highlight common parts in the past, such as mixin, renderless compontent, or HOC, none of these could provide the same high degree of flexibility as the Composition API. The biggest advantage of this new feature is that we can simultaneously extract the parts that we previously had to implement in the data, computed, and methods parts for a given component (with the Options API). Let’s take a brief example of how to use the Composition API in real-world situations.
As a first step, create a project using Vue.js (version 3). I will use vue cli for this purpose for the sake of speed. Once the project is complete, delete the example component, we will not need it. Clarify the project structure we will organize the code into. I put my components in the component folder under src, and at the same time I create a services folder into which I pack the reusable but “no-component” code that implements business logic. One file contains one service. If I would have to give an example of common services, there are, for example, services that implement various sorting and filtering or http calls.
We don’t usually want to write them as components, they can only be parameterized properly, but we want to see the given logic in general, as a module in the code. The Composition API as an implementation solution fits in perfectly with this idea.
The Composition API introduces a new part to the component code called setup. This is a function that can have 2 parameters, context and props. Within the setup, we can implement the parts that we wrote in the data, computed, and methods sections using the previously known Options API. Here we can define the internal state and functions of our component and here we can also use the common code snippets I call services.
In a lot of my projects, I needed tables that could be sorted by columns in ascending or descending order. We will create two tables that will use the same director service. This is a great, real-life example of why the Composition API is effective as an idea.
Of course, in an enterprise-sized project, we would have to go on to outsource all the tabular logic to a generic table component, which then uses the sorting service, but we won’t do that now because the article aims to introduce the Composition API, which will be enough extracting the service code from the tables.
The aggregation component of our application is called HomePage which only displays the two tables. The two tables are also simple, one listing users and the other listing products. The Composition API allows me to create a sort operation as a separate service, where I can work with reactive values if I want, which I can then make available in components that use the service.
In the example, I will store the sort direction in my service’s own reactive variable. I print this order value in both of my table components in the text of the buttons below the data. I will change the sort order only and exclusively within the sort service when necessary and in a clearly visible way, the component will be notified of this change immediately, proving the presence of reactivity.
The end result
The HomePage component contains the two tables (and a few lines of css code to highlight tables from the background):
The ProductTable and UserTable components
The ProductTable component shows a simple table with 3 columns and a button for sorting below. It defines the data rows for the sake of simplicity from the line of 25.
Line 33: use the order service to get its returned values which are the orderState and orderItems. OrderState is the inside state of the order service contains the direction value (“asc” or “desc”) and OrderItems is the sorting function itself. As you can see the whole sorting logic is separated from the component uses that. Imagine how useful this solution can be with 10 or more services within one component.
Line 35: do a sorting with the service at the component “loading time” (see the vue 3 lifecycle methods).
Line 37: return with an object contains state (component own - reactive -state), orderItems (sorting function) and orderState (the order service own state with the direction value). That’s an important moment because the Composition API needs this kind of return in order to work properly. After you returned with those things, the component’s template can use orderItems and orderState.direction as you can see in the line of 14.
Line 8: the state can be used in the template in a straightforward way.
The UserTable component is almost identical to the previously analysed ProductTable. The only difference is the data rows at the line of 25. This component can benefit from the sorting service just like the ProductTable component.
The sort service is nothing special, just a super simple sorting feature. It can sort the given arra of data by the content’s name property. I don’t validate the input values because it doesn’t matter from the Composition API example point of view. The important parts is the reactive state inside the service (or function or whatever you call it) and the return value at the end of the feature.
Remember: you have to return with EVERYTHING (functions, variables, etc) from the service in order to make it available on the component level.
The cool thing in Composition API is that the whole logic connected of a feature can be extracted into a separate part because you can “simulate” the data, method and computed features of Vue.js in one single code block if you’d like. With that idea I can made and used my separated sorting feature in any components in the same way.
I know, I know, it’s a super simple example. The sole purpose of this article is to draw your attention to the biggest benefit of the Composition API. If, like me, you use Vue.js for enterprise softwares, try replacing the usual Options API next time and you won’t be disappointed. What do you think about this topic? Share me your thoughts and experience in the comments. All the best!