Vue Composition API
The Composition API is a new set of functional APIs introduced in Vue 3. It aims to solve some problems encountered in Vue 2's Options API in large applications, such as scattered logic and difficulty in reuse. The Composition API allows us to organize and reuse component logic more flexibly.
What is the Composition API?
The core idea of the Composition API is to organize code related to the same logical function (such as state, methods, computed properties, watchers, etc.) together, rather than splitting them by options (data, methods, computed).
This approach makes code easier to read and maintain, especially when components become complex. It also makes logic reuse very simple and intuitive.
The setup Function
The entry point of the Composition API is the setup function. In Vue 3's single-file components, we typically directly use <script setup> syntax, which is essentially syntactic sugar for the setup function.
<script setup>
// All code written here is within the scope of the setup function
import { ref, onMounted } from 'vue'
// Reactive state
const count = ref(0)
// Method
function increment() {
count.value++
}
// Lifecycle hook
onMounted(() => {
console.log(`The initial count is ${count.value}.`)
})
</script>
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>In <script setup>:
- All top-level bindings (variables, function declarations) are automatically exposed to the template.
- We can directly use APIs imported from
vue, such asref,reactive,computed,watch, and lifecycle hooks.
Core API Overview
ref and reactive
Used to create reactive data.
ref(): Accepts an internal value and returns a reactive, mutable ref object. This object has a.valueproperty that points to the internal value. Typically used to create reactive variables of primitive types (strings, numbers, booleans).reactive(): Returns a reactive proxy of an object. It deeply converts the object, making all nested properties reactive. Typically used to create reactive objects.
import { ref, reactive } from 'vue'
const count = ref(0) // ref for primitives
console.log(count.value) // 0
const state = reactive({ // reactive for objects
user: 'John Doe',
posts: []
})
console.log(state.user)computed
Used to create computed properties. It accepts a getter function and returns an immutable reactive ref object.
import { ref, computed } from 'vue'
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // Error! Computed properties are read-onlywatch and watchEffect
Used to perform side effects when data changes.
watch: Precisely watches one or more data sources and executes a callback when they change. It is lazy and can access new and old values.watchEffect: Immediately executes a function and reactively tracks its dependencies, re-running when dependencies change.
Lifecycle Hooks
The Composition API provides a series of functions corresponding to component lifecycle events, such as onMounted, onUpdated, onUnmounted, etc. They accept a callback function that is called during the corresponding lifecycle stage of the component.
import { onMounted } from 'vue'
onMounted(() => {
console.log('Component is mounted!')
})Advantages Summary
- Better Logic Organization: Can put code for related functions together, rather than being forced to split by options.
- Better Type Inference: The Composition API mainly uses regular variables and functions, making it very friendly to TypeScript.
- More Flexible Logic Reuse: Can easily extract any logic (state, methods, etc.) into reusable "Composables" and use them across multiple components.