What is Composition API?

Nguyen Hoang - Aug 28 - - Dev Community

Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs:

Reactivity API, e.g. ref() and reactive(), that allows us to directly create reactive state, computed state, and watchers.

Lifecycle Hooks, e.g. onMounted() and onUnmounted(), that allow us to programmatically hook into the component lifecycle.

Dependency Injection, i.e. provide() and inject(), that allow us to leverage Vue's dependency injection system while using Reactivity APIs.

Composition API is a built-in feature of Vue 3 and Vue 2.7. For older Vue 2 versions, use the officially maintained @vue/composition-api plugin. In Vue 3, it is also primarily used together with the syntax in Single-File Components. Here&#39;s a basic example of a component using Composition API:</p> <p>vue<br> `<script setup><br> import { ref, onMounted } from &#39;vue&#39;</p> <p>// reactive state<br> const count = ref(0)</p> <p>// functions that mutate state and trigger updates<br> function increment() {<br> count.value++<br> }</p> <p>// lifecycle hooks<br> onMounted(() =&gt; {<br> console.log(<code>The initial count is ${count.value}.</code>)<br> })<br>


Count is: {{ count }}
`
Despite an API style based on function composition, Composition API is NOT functional programming. Composition API is based on Vue's mutable, fine-grained reactivity paradigm, whereas functional programming emphasizes immutability.

If you are interested in learning how to use Vue with Composition API, you can set the site-wide API preference to Composition API using the toggle at the top of the left sidebar, and then go through the guide from the beginning.

Reactivity API trong Vue.js có thể được dịch sang tiếng Việt là "API phản ứng" hoặc "API tính phản ứng".

Reactivity API cung cấp các công cụ để quản lý trạng thái phản ứng (reactive state) trong Vue.js, giúp các component tự động cập nhật khi dữ liệu thay đổi. Đây là một phần quan trọng của Vue.js, đặc biệt khi sử dụng Composition API.

Dưới đây là một số thành phần chính của Reactivity API:

ref: Dùng để tạo một giá trị phản ứng đơn lẻ. Ví dụ:

javascript
Copy code
import { ref } from 'vue';

const count = ref(0);
count là một giá trị phản ứng. Khi bạn thay đổi count.value, Vue.js sẽ tự động cập nhật các phần của giao diện người dùng sử dụng giá trị này.

reactive: Dùng để tạo một đối tượng phản ứng. Ví dụ:

javascript
Copy code
import { reactive } from 'vue';

const state = reactive({
count: 0
});

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player