Table of contents
1.
Introduction
2.
Why Composition API
3.
Composition API
4.
Provide/Inject API
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Composition API | Provide/Inject

Author Parth Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Using significant Vue2 components made it extremely difficult to read, comprehend and maintain the code and its process. As an example, let us consider the creation of a search bar. The search bar requires a data option to define its properties and a method option to implement the search login. Furthermore, as the logic component options such as props, computed, and lifecycle methods are implemented, effectively repeating the coding logic in multiple places, making the code significantly hard to comprehend. 
This problem of code being spilled up and repeating itself at multiple places is solved using the Composition API. The Composition API keeps our code logic together to make the code more readable.

Why Composition API

In the above section, we received a general sense of why Composition API is required and comes in handy. But, to cement this knowledge, let’s check out this example.

export default {
  components: { repoFilters, repoSortBy, repoList },
  props: {
    user: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      repo: [], // 1
      filters: { ... }, // 3
      sQuery: '' // 2
    }
  },
  computed: {
    filteredrepo () { ... }, // 3
    repoMatchingsQuery () { ... }, // 2
  },
  watch: {
    user: 'getUserrepo' // 1
  },
  methods: {
    getUserrepo () {
      // using `this.user` to fetch user repo
    }, // 1
    updateFilters () { ... }, // 3
  },
  mounted () {
    this.getUserrepo() // 1
  }
}
You can also try this code with Online Javascript Compiler
Run Code

In the above example code, the code is cataloged with the help of the component's options (data, computed, methods, watch). Currently, the code performs searching, filtering, and repo fetching. Still, now, it is noticeable that as the number of options increases, the code is bound to be more complex and intimidating. Without Composition API, the code appears to be fragmented and is thus needs to be packaged nicely into one unit.
Therefore, Composition API is used.

Composition API

Now that we are familiar with the purpose and requirements of Composition API, let us move towards how exactly it works and is used.
The core idea behind Composition API is to replace all the component's options (data, computed, methods, watch) into one setup() block.

From To
{
data ( ) {
return { name:’Coding Ninjas’ };
 } ,
methods:{ doingSomething( ){..........  }   }
}
You can also try this code with Online Javascript Compiler
Run Code
{
   setup() {
   const name=ref(‘Coding Ninjas’);
   function doingSomething() {........}
   return { name,doingSomething  };
}
}
You can also try this code with Online Javascript Compiler
Run Code

 

The setup component is created after the execution and should be treated as a function that accepts props. The return statement inside the setup function is given to all the components, such as properties and methods.
Here is a complete sample code that uses Composition API to justify the above statement.

setup() {
    const goals = ref([]);
    const filteredGoals = computed(function() {
      return goals.value.filter(
        (goal) => !goal.text.includes("Angular") && !goal.text.includes("React")
      );
    });
    function addGoal(text) {
      const newGoal = {
        id: new Date().toISOString(),
        text: text,
      };
      goals.value.push(newGoal);
    }
    return {
      filteredGoals: filteredGoals,
      addGoal: addGoal
    };
  }
};
You can also try this code with Online Javascript Compiler
Run Code

Composition API introduced the functional approach that made the code much shorter, manageable, and comprehensible. 

Provide/Inject API

The Provide/Inject APIs pass data to a component that resides down the component tree without giving props at every level manually.
To understand the above statement, let us consider the following case.
The components D, I, and H require the address property in the app component. With the help of props, we can pass it to components A, B, and C and keep repeating the passing process until the component receives the required property. However, this process of forwarding the props from one component to the other is only suitable for trim component levels. It is much better that we somehow pass the data directly to the components without forwarding props.
To do so, we do two things:

  1. Provide data to the app components
  2. Inject the data to the component directly

To use Provide,

import { provide } from 'vue'
You can also try this code with Online Javascript Compiler
Run Code

In the component that contains the data.
To use Inject,

import { inject } from 'vue'
You can also try this code with Online Javascript Compiler
Run Code

In the component that needs the data to be injected.
App.vue

export default {
 name: "App",
 components: {
   HelloWorld
 },
 provide:{
   address:"Kohat Enclave"
 }
};
ComponentH.vue
export default {
 name: "ComponentH",
 inject:[‘address’]
};
You can also try this code with Online Javascript Compiler
Run Code

With the help of Provide and Inject APIs, we provided data to component H without passing it as an argument to all of component H’s parent components. 

FAQs

  1. What is Composition API?
    The Composition API is an extension to the Options API used to reduce the code complexity using functions instead of options such as methods and properties.
     
  2. How do Provide/Inject APIs work?
    The Provide/Inject APIs work by injecting data to a component without passing it using props. This saves the programmers time and makes the code less complex.

Key Takeaways

In this article, we learned about Composition API and how it reduces code complexity by making it easy to comprehend. We also learned with practical examples the working of the super function. Then, we acquainted ourselves with the Provide/Inject APIs used to provide data to a component without the need for props. Thus, saving coding time and making the code less complex. However, this isn’t enough, as there is always much more to explore and learn about this vast field of Web Development. To know more about Vue and its intricacies, check out the articles on Vue or enroll in our highly curated Web Development course.   

 

Live masterclass