Next article

Choosing the best IDE for React development might be challenging. Thinking about the type of development you'll be performing might help simplify the process. Whenever...

A Complete Guide to Vue Composition API

The Vue Composition API is a game-changer for Vue js development since it allows for a powerful and versatile means of building Vue components. By using Composition API, you may simplify the management of complicated programs and increase code reuse.

Let’s explore the power of API and Vue components in Vue 3 architecture. In this article, we will discuss what the Vue Composition API is, how it differs from the Options API and the Component API, its main features, and how to use the API with Typescript. Hire Vue developers in India to cater all your frontend development requirements.

Table of Content

1. What is Vue Composition API?

Vue Composition API is a function-based API that increases code readability, simplifies API usage, and aids in the upkeep of component logic. Vue 2 users may get access to Composition API by installing the @vue/composition-aPI plugin.

You can use the Composition API to organize your code by breaking it down into manageable chunks that can be grouped together. You can also use it again if necessary. The code for the parts is dependent on their characteristics or capabilities. It works well for sophisticated and large-scale programs.

Vue’s Composition API was introduced to address the limitations of the Options API when multiple components grow in size. Some restrictions of the Options API are as follows.

  • Limited Reusability: Inefficient logic and component reuse practices.
  • Lack of organization: As the size of the component increases, readability decreases and affects the code quality.
  • Difficulty in tracking component dependencies: As the scope of a project grows, the complexity and difficulty of its code also grows.With the Options API, it can be challenging to track the dependencies of computed properties and watchers. This can make it harder to ensure that the component correctly reacts to changes and updates its state.
  • Adds complexity to working with ‘this’ in Typescript and causes confusion.

2. Why Composition API?

2.1 Better Reusing Logic

Reusing logic in the manner of Composable functions is one of Composition API’s key benefits. It fixes every problem with mixins, the main technique for reusing functionality in the Options API.

2.2 More Flexible Code Organization

There is now no need to leave the current choices block since composition API addresses the same logical concerns. Since you don’t have to reorganize the code to remove it, you can now easily copy and paste a section of code into a new file. The long-term maintenance of big codebases depends on this reduced barrier for reworking.

2.3 Better Type Inference

The majority of the Composition API is made up of simple variables and functions, which are inherently type-safe. Composition API code benefits from comprehensive type inference and seldom requires type hints. TypeScript and vanilla JS both have almost similar syntax for the same component API. This opens up the possibility of partial type inference to consumers of plain JavaScript as well.

3. Example of the Composition API

In the Composition API, rather than the Vue instance structure familiar to Options API, logic is implemented by importing Vue functions.

The following code is a basic example of a Vue application that uses the Composition API to reduce the number of typewriters in storage when the user clicks a button:

Example

App.vue:

<h1>Typewriter Inventory</h1>
  <img src="/img-typewriter.jpeg" alt="Typewriter">
  <p>Typewriters left in storage: {{ typeWritersLeft }}</p>
  <button>Deduct 1</button>
  <p style="font-style: italic">"{{ inventoryMessage}}"</p>
 
 
 
  import { ref, computed } from 'vue'
 
  const typeWritersLeft = ref(10);
 
  function remove(){
    if(typeWritersLeft .value&gt;0){
      typeWritersLeft .value--;
    }
  }
 
  const inventoryMessage= computed(
    function(){
      if(typeWritersLeft .value &gt; 5) {
        return "Many left"
      }
      else if(typeWritersLeft .value &gt; 0){
        return "Alert! Very few typewriters are left"
      }
      else {
        return "Typewriters are out of stock"
      }
    }
  )

The setup property, seen on line 9 above, simplifies the use of Composition API. For instance, the setup element enables the usage of variables and functions within the <template> itself.

On line 10, you’ll need to import ref and compute before using them. When working with the Options API, declaring reactive variables or employing computed properties does not need the usage of any other libraries.

The typeWritersLeft property is marked as reactive on line 12 using ref, and the value “10” is set as the initial value.

If the typeWritersLeft attribute is marked as reactive and if its value changes, the line beginning with “typeWritersLeft ” in the <template> will be re-rendered to reflect the new value. When an application is constructed using the Option API, reactive properties are automatically created if they are required.

If you wrote the code above using the Options API, you would specify the ‘remove()’ function stated on line 14 using the Vue property ‘methods’.

On line 20, the ‘inventoryMessage’ computed property would be specified in the Vue property ‘computed’ if the code was written via the Options API.

4. Vue Composition API vs Options API

The primary differences between Vue Composition API and Options API components are as follows. Let’s quickly break it down into code and grasp it:

4.1 Structure

The Options API’s simplicity and readability are among its primary advantages. It adheres to a straightforward, declarative paradigm common to many web app developers and is thoroughly covered in the Vue docs. For this reason, it is recommended for those who are just getting started with Vue JS.

It might be challenging to use the Options API for more sophisticated applications due to its restrictions. As the complex components grow, it might become difficult to handle a huge number of alternatives. This can cause “option explosion,” when a formerly manageable part of a system grows to become too big and unmanageable for practical use.

Let’s see the structure of Composition and Options API with the below image:

Options API vs Composition API

4.2 Example of Composition API vs Options API

// Using the Options API
  export default {
   data() {
     return {
       counter: 0
     }
   },
   computed: {
     doubleCount() {
       return this.counter * 2
     }
   },
   methods: {
     increment() {
       this.counter++
     }
   }
  }
 
  // Using the Composition API
  import { ref, computed } from 'vue'
 
  export default {
   setup() {
     const counter= ref(0)
     const doubleCount = computed(() =&gt; counter.value * 2)
 
     function increment() {
       counter.value++
     }
 
     return {
       counter,
       doubleCount,
       increment
     }
   }
  }

The Vue Options API and the Composition API both contain a reactive property named counterand a derived value named doubleCount that operates on the value of counter. These variables are defined differently by the two APIs; the Options API makes use of the data, computed, and methods options, whereas the Composition API makes use of the ref and computed functions inside the setup function. We may avoid using the methods option and instead define the increment function inside the setup function thanks to the Composition API.

5. Key Features of Vue Composition APIs

The Vue Components includes several tools that aid in code modularity, code reuse, and developer productivity. Vue’s Composition APIs are mostly used for the following features:

5.1 Reactivity API

Vue Composition API’s reactivity is a core feature that enables the seamless monitoring and upgrading of data dependencies in the UI. Through its reactive and ref methods, the Composition API implements reactivity.

For efficient UI responsiveness and change tracking, the ref functions generate a reactive reference to the value. Therefore, it is possible to directly create reactive state, watchers, and computed state using ref() and reactive().

Using the Reactivity API, programmers can create Vue 3 applications that are both adaptable and quick to respond to user input.

5.2 Lifecycle Hooks

Component lifecycle events may now be managed with more ease and versatility thanks to the introduction of the Composition API and the use of lifecycle hooks. It features two hooks, “onMounted” and “onUnmounted,” which provide granular insight into the lifetimes of their respective single file components.

Lifecycle Hooks

As shown in the above flow chart, when a component is first added to the DOM, code from the onMounted hook is run. It offers a hook for activation that may be used to retrieve data from an API, configure external dependencies, and so forth.

When a component’s reactive dependence is unmounted, the onUnmounted hook is executed. Using the hook, you may instantly react to modifications and refresh the vue component. When a part is dismounted, it allows for cleaning procedures to be performed.

5.3 Dependency Injections

To create interactive and easily maintained Vue.js applications, this component API is essential. Components can now trust injected dependencies rather than hard coded ones thanks to Dependency Injections. The below flow chart depicts the working of Vue Dependency Injections.

Dependency Injections

The supply method allows a parent component to retrieve information for its child components. You can manage the component hierarchy more efficiently.

At the same time, the inject function provides a route to the value-supplying parts of a system. This feature improves the code maintainability of Vue 3 applications by allowing multiple components to utilize shared resources across layered components.

6. Composition API with TypeScript

Vue Composition API with TypeScript

Vue 3’s code is written in TypeScript, so Vuejs applications can use TypeScript and the Composition API. You can make use of features like static type checking, type inferences, and IDE auto-completion when you use the Composition API in conjunction with Vuex 4 Typescript.

To use Composition API Typescript, nevertheless, you must first download and set up the requisite dependencies. With Composition API, you can specify the data and computed properties methods that comments will receive, unlike functional programming languages. Vue apps are versatile and adaptable, and you may increase cooperation in huge codebases by catching mistakes early on.

7. Conclusion

To sum up, the Composition API is a great asset to the Vue JS ecosystem, allowing for cleaner code, faster execution, and simpler reuse of functionality across different parts of a project. Vue developers should think about this strong addition, but it is not meant to replace the Options API. The Composition API is a powerful tool, and while you may end up using the Options API instead (or both), it’s worth looking into if you haven’t already.

8. FAQs

8.1 Is it possible to utilize the Composition API for standalone files?

The <script> elements of the SFC do indeed define composition methods and leverage the Vue Composition API to acquire the relevant Vue functions.

8.2 Does the Vue.js Composition API have any effect on performance?

Vue.js apps do not suffer a performance hit due to the API. But if not properly arranged or organized, complicated composition functions may have an adverse effect on performance.

8.3 What about replacing Vuex with the Composition API?

Composition API is not a substitute for Vuex. The combination of API and Vuex can boost efficiency and response.

8.4 To what end may the Vue Composition API be put to use?

Download Vue 3 and include the required methods, like script setup and createApp, to use the Vue Composition API. Then, you can use compositions to specify your components based on the functions and methods returned by the setup function.

profile-image
Hardik Dhanani

Hardik Dhanani has a strong technical proficiency and domain expertise which comes by managing multiple development projects of clients from different demographics. Hardik helps clients gain added-advantage over compliance and technological trends. He is one of the core members of the technical analysis team.

Comments

  • Leave a message...