vuejs Archives - Bistec Global Services - Services enabled, digitally!
BLOG

Tagged Post

vuejs

Vue Js Composition API and Component Reusability

February 3, 2022

Vue 3 Composition API provides a new approach to organizing data models and functions. Previous options of API don’t provide features to organize models or business logic in a logical manner. Composition API provides a great feature to organize codes, in a more reusable manner and it improves the readability of big components.

Option API distributes codes among data block, computed blocks methods, and watch functions. Code has been spread in all the places there is no logical fragmentation. That structure is what makes it difficult to understand and maintain a complex component.

However, when we are working with bigger code blocks it’s convenient to fragment code blocks based on logical concerns. It would be much nicer if we could collocate code related to the same logical concern. And this is exactly what the Composition API enables us to do.

Vue - Composition API

The Problem

If you have experience with Vue Js 2, you must have seen the Option API, where the codes aren’t fragmented in a logical manner based on its functionality. A component might look like this. If we apply different color codes for code fragments according to the Vue Composition API RFC showing how code fragments will be.

Vue - color codes

How Composition API resolves

Here, the goal is to fragment codes based on their feature / logical functionality. Using Composition API, we can extract this logic and place it in separate files. And we can consume those inside the Setup method in Composition API. The separation of options obscures the underlying logical concerns. In addition, when working on a single logical concern, we have to constantly “jump” around option blocks for the relevant code

Composition API Using Nuxt Js

Nuxt Js provide Composition function using Nuxt Composition API. @nuxtjs/composition-api module that brings first-class Composition API support to Nuxt. The @nuxtjs/composition-api package is a wrapper over a @vue/composition-api plugin which means that along with Nuxt-specific utilities it contains all “standard” Composition API functions like ref or computed.

Before starting the feature of the Composition, first, we will look into how Nuxt Composition API addons facilities to us to work with Composition in Nuxt Project. To enable Composition in Nuxt project we have to setup NuxtJs Composition API.

The installation is straightforward, just like with every other Nuxt module. First, we have to install the package:

npm install @nuxtjs/composition-api –save

And register the module in our nuxt.config.js

{ buildModules: ['@nuxtjs/composition-api' ] }

The module is registering @vue/composition-api plugin under the hood so we can immediately use its features in our project without any additional code.

Server-side

The @nuxtjs/composition-api provide SSR capabilities within Composition.

UseFetch which is a Composition API wrapper for a well-known Nuxt fetch that is commonly used to fetch asynchronous data (both on a server and client-side)

It does two things:

It makes sure that the asynchronous function that passed as its argument resolved. Then the result conveyed to the client-side through the window. NUXT object and picked up by your client-side code as its initial state.

It prevents the client-side execution if navigation has been made on a server-side. Because of that, we are not performing unnecessary network calls if we already have the data from the server-side fetch.

To make use of useFetch in our composable we just need to wrap it around our asynchronous code:

Vue - asynchronous code

Using Nuxt Context in your composable

Among data-related server capabilities, Nuxt composition API is delivering a set of composable to interact with other composable APIs. One of the most helpful features is the use of Context. As represented in the name, it facilitates us to access Nuxt context inside our composable. We can use this instance to access router, store, and properties via Nuxt Modules.

In Vue 3 Composition, Vue Context is accessible inside the Setup() method only. It’s not allowed to accessed outside. Therefore, if we want to access the Context in different Compose files, we have to pass context as a parameter to the specific file. With the help of the use Context () method we can access Context Object inside any Composition API.

How to Modularize Components

Let’s see how we can organize our component by feature and reuse our code across other components. In this below example it’s a Student Portal that has three main feature areas; those are Course Enrolment, Showing Progress Report, Showing Student Profile. If we see the functionality of the student portal, we can clearly identify that it has three modules as follows.

  1. Enrollment
  2. Progress Report
  3. Student Profile

Let’s see how we can organize the code using Composition API.

Modularize Components

Here Enrollment, Progress Report, and Student Profile moved to different files. Its related fields and methods are also placed in the same file. Therefore, it’s more human-readable and meantime maintainable. And we can use the above compose section anywhere in our application as used on this page.

Building Reusable UI Vue Component

There are two approaches available to build reusable components in the Vue application. Both have their strength and weakness. Those are using Property and using Slot. We have to select the correct approach based on the needs.

Using Props

For example, there is an Address Component that used to capture the address of the student. The same component has been used to capture local addresses and foreign addresses as well. So based on the country, the address fields should changed. This has been achieved using Props for the component. The component has multiple props to change the behaviour of the component.

Props01
Props02

This approach is suitable for small components. If the number of props increases, it’s difficult to manage the component because we are introducing logic inside the component to maintain the state. It’s difficult to understand.

To handle this scenario with Vue 2.6 Slot directive has been introduced. Through this, we can distribute the content to the component. So rather than keeping the HTML content in a component and changing the behaviour based on the props. We can set the HTML content to the component from the outside.

Slot Directive

So, we understand the whole concept from the definition of slots it’s about making components reusable. Now, we’re going to dive in with some examples showcasing Vue slots and talk about how to make use of them.

We will take the same example and see how we can use Slot instead of Props.

Vue - Slot directive

You can notice in the above picture that we have removed Drop down and Input Control and we have placed <slot> tag. This is going to work as a placeholder and when we are using this component we have to define the HTML Content for this Slot as given below.

HTML Content

Through this, we can distribute the content to outside of the component. Therefore, we are able to control the component behaviour from the outside.

Conclusion

We have seen how we can use Nuxt Composition API to fragment code in a logical manner and how we can reuse them among the components. Meantime we can create reusable UI Components using Slot directives. The goal of the Composition API is to increase readability and facilitate us to create components in a more reusable manner.

Authored by Deepakumar Ganeshamany @ BISTEC Global

Source Code: https://github.com/bistecglobal/VueCompositionAndComponents

 
Let's talk

We love connecting

We are here to help and support you.

If you believe that we can help you or your businesses requirements - do feel free to drop your details here and don’t hesitate to give us a ring.

Connecting with us on LinkedIn works best.

  • Footer Email