DEV Community

Apiumhub
Apiumhub

Posted on • Originally published at apiumhub.com on

Vue 3 Composition API

In this article, we assume that you know the basics of Vue 3. In the cited article, the main changes from Vue 2to Vue 3are explained, as well as the basis for understanding how composition API functions. The latter would be the main topic of this article: Vue 3 Composition API.

Vue 3 Composition APIs

The change from Vue 2 to Vue 3 offers several options to developers when assembling the logic of a component. We can continue using the Options API as we were doing in Vue 2 or use the Composition API.

Advantages of Composition API

The main advantage is the ability to extract the logic and be able to reuse it in different components, making our code more modular and easier to maintain. So we avoid having to use mixins, which was the way to reuse logic in Vue2.

If we continue talking about the organization, in Options API, if we explore our component, we will realize that each component is in charge of many responsibilities that will be forced to be divided into different parts of the code. That forces us to scroll up and down if the file has hundreds of lines, making it more complicated than it should be. Therefore, if we try to extract the logic in reusable parts, although it may involve a little more work, we will see that the result is much cleaner and tidier, we can see it in the following image:

structure

Another important advantage is that it allows functional programming, unlike the Options API which isobject oriented.

Code written using the Composition API is more efficient and modifiable than Options API code, so the bundlesize will be smaller. This is because the template in our <script setup> is compiled as an inline function within the same code scope. Unlike the thisproperty, the compiled code can directly access the variables without a proxy. Because of this, it helps us to have less weight by being able to have simplified variable names.

The new API allows you to take full advantage of Javascript by defining the behavior of our component,async/await, promises, and facilitates the use of third-party libraries such as RxJS, among others.

Disadvantages of Composition API

The main disadvantage is that it forces developers to learn a new syntax and way of organizing code. This can have a learning curve for those who are used to Options API. Still, it is designed to be simple and easy to learn, so the curve should be fast.

First steps

Template:

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>
Enter fullscreen mode Exit fullscreen mode

Options API:

<script>
export default {
  // Properties returned from data() become reactive state
  // and will be exposed on `this`.
  data() {
    return {
      count: 0
    }
  },

  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  methods: {
    increment() {
      this.count++
    }
  },

  // Lifecycle hooks are called at different stages
  // of a component's lifecycle.
  // This function will be called when the component is mounted.
  mounted() {
    console.log(`The initial count is ${this.count}.`)
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Composition API:

<script setup>
import { ref, onMounted } from 'vue'

const count = ref(0)

const increment = () => {
  count.value++
}

onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>
Enter fullscreen mode Exit fullscreen mode

Comparison with React Hooks

Compared with React Hooks, the logic is the same, but with some differences.

React Hooks:

  • Hooks are invoked whenever there is an update of the component.
  • Variables declared in a hook closure may become obsolete if the correct dependencies are not passed.
  • Heavy computations must use useMemo which will require us to pass dependencies manually.
  • The Event handlers passed to secondary components cause unnecessary code updates by default. Neglecting this causes an excessive update affecting performance almost without realizing it.

Vue Composition API:

  • The setup()or <script setup> code is invoked only once.
  • Vue’s reactivity system in runtime retrieves the reactive dependencies, so we don’t need to declare them manually.
  • There is no need to manually control the callback functions to update the child components. Vue ensures that components are only updated when they are really needed.

That said, react hooks were a major source of inspiration for creating the Composition API, but trying to solve the problems mentioned above.

FAQs

Will Options API be deprecated?

No, it’s not planned, it’s part ofVue and there are many developers who love it. Besides, many of the benefits of the Composition API can only be felt in large projects, so Options API is still a good choice for small and medium projects.

Can I use both APIs together?

Yes, you can use Composition API using the setup() method in the Options API. However, it is recommended only if you have your code in Options API and you need to integrate some library written in Composition API.

Is the Composition API compatible with Vue2?

No, you must upgrade your project Vue 3 in order to use the Composition API.

Conclusion

In conclusion, both APIs are valid for the logic of a Vue component. The Composition API offers us a functional and reusable way to organize our code, while Options API offers us the traditional solution: Object oriented. Still, if what you want is better performance, better code readability and you are in a large project, your choice should be Composition API.

Top comments (0)