Vue Composition API

VueJS, being a robust JavaScript framework, is a popular choice for building modern web applications. Composition API is one glaring reason behind it. Top VueJS development companies use this feature to create large and complex applications. You can easily maintain and scale a complex codebase with it. 

This article serves as a guide to understanding the Vue composition API along with its features and benefits. It also demonstrates how to install and use composition API in Vue.

1. What is the Vue Composition API?

First introduced as a built-in feature of Vue 3, Composition API allows developers to write Vue components using imported functions. In Vue v2, this task was accomplished by declaring options. But now, you can use the composition APIs in old versions through the @vue/composition-api plugin.

Composition APIs offer a robust and flexible approach to organizing the code and reusing it across multiple components. The set of imported functions they provide helps you compose logic in a functional style. It’s way better than the traditional use of options-based syntax because composition API makes it easy to handle complex and large-scale apps and makes its code more readable.

2. Key Features of Vue Composition APIs 

This section discusses the primary features that make composition APIs a valuable tool in app development. 

2.1 Reactivity APIs

Reactivity is useful for automating the tracking and updating of data dependencies in a user interface (UI). The Composition API implements reactivity using reactive and ref() functions(). 

The Vue developers created a reactive reference for value using the ref functions to facilitate effective tracking of changes and ensure UI reactivity. The ref() and reactive() functions help directly create reactive state, computed properties, and watchers directly. In short, you can build a responsive and flexible Vue 3 application using the reactivity API. 

2.2 Composition Functions

These functions promote component-based development as they break down the complex parts of the code into small and manageable units within the same component. They isolate specific areas of concern within a component to handle its logic well. This leads to better code organization and reusability. Data manipulation, computed properties, and custom logic are well-known examples of composition functions. 

2.3 Lifecycle Hooks

You need a specific point in a component lifecycle to implement custom logic. Vue provides different options in the form of lifecycle hooks, such as created and mounted. Vue developers use these hooks to perform specific actions, like creating, mounting, or updating a component.

Lifecycle Hooks

3. Benefits of Composition in Vue.js

Using composition APIs in VueJS development offers several benefits. Here are a few of its advantages: 

3.1 Improved Code Organization

The Vue composition API offers a better approach to organizing your code. The setup function allows you to group related code based on functionality rather than type. With that, maintenance, navigation, and scaling of a codebase becomes easy, especially if it is a complex application.

3.2 Logic Reuse

Breaking down complex functionality into small, maintainable units makes it easier to share them across different projects. With Composition API, you can extract reusable logic and import it into the functions that you want to use in any Vue component. This approach not only encourages logic reusability but also reduces code redundancy. 

3.3 Better TypeScript Support

Front-end developers prefer TypeScript for its better IDE support, which helps in writing robust code. It was challenging to adopt TypeScript with Options API in Vue. But with the advent of composition APIs, Vue developers can enjoy a complete type inference with less need for manual hints.

All the functions and variables in Composition API are type-friendly. This offers better type-checking and auto-completion, resulting in enhanced productivity and a better development experience.

3.4 Flexibility

Composition in Vue allows developers to build flexible user interfaces. This enables them to experiment with different combinations of components to create dynamic and complex UIs. It is important to mention that the goal remains the same; to design an aesthetically pleasing and user-friendly interface. The Composition API helps you be creative about it.  

3.5 Better Performance

Your Vue code runs faster, thanks to the composition API. This approach reduces the amount of code that needs to be loaded and executed by breaking down complex functionalities into smaller components. As a result, loading times decrease, leading to improved performance. 

The render functions and scoped slots in Vue composition API help speed up rendering and eliminate unnecessary DOM updates, leading to an improved user experience. 

3.6 Easier Testing

When Composition API breaks down complicated functions into small, independent components, testing becomes much easier. You can directly test these functions in an isolated environment without mounting a Vue component. This approach improves the speed and efficiency of your tests.

4. Basic Example of Vue Composition API

The Vue Composition API is used in the above code for the following: 

Reactive State Creation: A reactive variable named wicket is created using the ref function. Because it is initialized at 0, the wicket acts as a reactive reference. So, if any changes are made to the wicket’s value, they will be reflected in the DOM automatically.

const wicket = ref(0);

Function Definition: In the setup function, a defined function named addWicket increases the wicket’s value if called. 

const addWicket = () => {
wicket.value++;
};

Returning Reactive Data and Methods: You can access the method addWicket and a reactive variable wicket directly from the template. Because the setup function returns the object consisting of them both. 

return {
wicket,
addWicket
};

Template Binding: The interpolation ({{ wicket }}) bounds the reactive variable wicket to the displayed content in a template. Meanwhile, the @click directive links the event of a button click with the addWicket function. 

<p>Wickets: {{ wicket }}</p>
<button @click="addWicket">+ Wicket</button>

With the composition APIs, you can easily define the functions and reactive state in the setup function. This streamlines the logic organization and state management processes which help you write a clean and easy-to-maintain code. 

5. Installing Composition API

Composition API  is a built-in feature in Vue 3, so, you don’t need to install it for Vue 3 projects. But it doesn’t come by default in Vue 2. In that case, install Composition API through NPM.

# NPM

npm install @vue/composition-api -- save

Next, import composition API in your main.js file. 

// Main.js
import VueCompositionAPI from "@vue/compostion-api";
Vue.use(VueCompositionAPI);

6. Using the Composition API in a Vue.js Component

Importing the ref() and reactive() functions from the Vue package and then defining a setup function allows you to use the composition API in a Vue component. The setup function acts as a lifecycle hook that helps you set up the reactive data and functions. It must be executed before creating the component.

<script>
import { ref, reactive } from 'vue';
export default {
  setup() {
    // Your Composition API code goes here
  },
};
</script>

7. Composition API with TypeScript

The utilization of Vuex4 with TypeScript and the composition API offers benefits such as type inferences, static type checking, and IDE auto-completion. But to enjoy these benefits, you first have to install the required dependencies and make other necessary configurations to use TypeScript. 

First, wrap the object of your component with defineComponent.

import { defineComponent, reactive, onMounted, ref } from "vue";
import Cricketerfrom "@/models/Cricketer";
export default defineComponent({
    name: "App",
    setup() {
        ...
    }
});

Now, you can use types in your set up:

const cricketers= reactive([] as Array<Cricketer>);
const cricketer= ref(new Cricketer());
const isLoading= ref(false);
const information= ref("");

The variables are inferred as types in the above code. The following APIs are also typed to reduce the chances of passing off wrong data. IntelliSense in TypeScript is a big help in such cases especially if you are using VS Code. 

Composition API with TypeScript

8. Conclusion

While the options API is helpful for object-oriented programming, the Composition API is changing how we organize code. It allows for logic reuse and supports component-based development. Its benefits include better app performance and better code readability. Moreover, it’s an ideal fit for complex and long-term projects.

FAQs

What is the difference between Vue option API and composition API?

Options API depends on a single object that contains various options, whereas the composition API relies on composable functions. Hence, the Composition API is an ideal choice for complex components or applications, whereas the Options API is a right fit for simple components or applications. 

What is the method composition API in Vue?

Composition API is a robust and flexible way to write components in Vue. It simplifies complex functionalities and promotes logic reusability.  

Can I use composition API in Vue2?

Yes, you can use the composition API in Vue2 by installing the @vue/composition-api as a plugin via Vue. use().

profile-image
Parind Shah

Parind Shah is responsible for frontend innovations at TatvaSoft. He brings profound domain experience and a strategic mindset to deliver exceptional user experience. He is always looking to gain and expand his skill set.

Comments

  • Leave a message...