advertisement

[5] How to use Composition API in Vue.js

A beginner's guide to leveraging the Composition API in Vue.js for modular and reusable code.

Inertia JS logo

A brief introduction to Composition API

Composition API is an umbrella term that covers different APIs. It allows the component author to use imported functions instead of declaring options. As a result, the following APIs are available:

  • Reactivity API
    • ref()
    • reactive()
  • Lifecycle Hooks
    • onMounted()
    • onUnmounted()
  • Dependency Injection
    • provide()
    • inject()

It is a built-in feature of VueJS3. However, it is available for Vue2 also with a plugin. (https://github.com/vuejs/composition-api). And it works with the script setup syntax as well.

Although it is NOT functional programming, It uses Vue's mutable fine-grained reactivity paradigm. 

What are the benefits of using Composition API?

So Competition API performs better in five main area over the Options API are:

  • Better Logic Reusability
    • Because of the composable functions.
    • Because It makes possible to write clean & efficient logically reusable
    • And due to we do not need to use mixins
  • Flexible Code Organization approach
    • Options API can be viable for small projects.
    • However, beyond a certain complexity threshold, the Options API becomes limited.
  • Type Interface (provides TypeScript compatibility)
    • This feature helps tp write more robust code
  • Smaller production Bundle althouh you will not see the benefits in performance point of view
    • Due to the script setup is more efficient and minification-friendly than the Options API approach

You can check my mindmap above for more Composition related info or check the spec of the Composition API.

Conclusion & Closing

In the previous VueJS related topic, I detailed the Options API main features [Options API1, Options Api2]. In this post, I have tried to dive into the Composition API. I did so because I use VueJS on the Front-End side for a project, so I need to become familiar with this topic. I hope these notes will have benefits for others, not just me. Anyway here is a cheatsheet about Composition AP.

advertisement