Introducing Composition API in Vue3 – VueJS

Tram Ho

Overview

Vuejs is one of the hottest Javascript Frameworks today. Perhaps because of the simplicity, flexibility, ….etc the advantages that it brings. Currently Vue 3 version is stable. I dug into the docs on the homepage to see the changes. Boom, Composition API

Content

1. Introduction

According to the introduction on Vue3’s homepage, the Composition API  is mentioned starting from the disadvantage of being difficult to reuse, maintain the code as the application gets bigger and bigger.

I would like to take an example from Vue3’s introduction homepage Composition API

As the project grows, when we want to add a function we will find it difficult to choose a suitable place to write code. (data, methods, mounted,…) Too many issues to take care of.

To solve this problem, Composition API was born. To start working with the Composition API, we need to declare a new option component  setup.

And starting from here, you can temporarily forget about other commonly used option components such as  data,  methods,  computed,  watch,  lifecycle  of Vue. Everything is workable in the  Composition API. À mà khoan, các bạn đừng vội quên vội, mình cần các bạn nhớ để so sánh nó cách code trước và sau khi Composition API ra đời.

2. Ref, reactive

ref, reactive are hooks used in Composition API to define data, just like we define data in option data

Ok now let’s compare the two ways of coding

image.png

Trong Composition API, chúng ta dùng hook ref hoặc reactive để định nghĩa một biến reactive.

When you need to use or change this variable value in the Composition API:

Too simple, isn’t it? I just need hello.value is to get the value of that variable.
For reactive:

For reactive, there will be no need .value

when we need to use that variable on vue template, we just need to return an object with that variable.

VD:

3. Methods

In Vue2, when we need to declare a function or a method, we will define it in the option component methods , then in the Composition API you can define it like a regular function and return it like ref  and reactive I said in part 2

4. Computed

In the Composition API, computed is defined via the computed hook.

5. Watch

In the Composition API, observing a variable is done via hook watch. Especially Vue3 supports multi-variable watch

6 Lifecycle

In the Composition API, most lifecycles exist

For specific lifecycles available in the Composition API, refer to: https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html#lifecycle-hooks

Summary

In this article, I gave an overview of the Composition API in Vue3. You may be familiar with how to code in Vue2, but trust me if you try the Composition API you will find it really cool.

Share the news now