Getting Started with the Composition API
🎯 Introduction
By the end of this article, you will understand the ideas behind Vue 3's Composition API and know how to use setup(), ref, reactive, lifecycle hooks, computed, and watch. You will move beyond Vue 2's reliance on this and organize component logic more flexibly, improving productivity and maintainability as you learn Vue 3.
✨ Why the Composition API?
Vue 2.x uses the Options API: familiar options such as data, methods, computed, and watch. Although straightforward, this approach can scatter code as component logic grows. When a component has multiple features, the code for each feature is spread across data, methods, and computed, making its overall behavior hard to follow.
The Composition API addresses this by grouping related logic together and organizing code through functions, improving reuse and clarity.
⚙️ How and When to Use setup()
setup() is the entry point for the Composition API and runs when a component is created. Use it to declare reactive state, define functions, and register lifecycle hooks. Properties of the object returned by setup() are exposed to the template.
Here is a simple component:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment,
};
},
};
</script>
All component logic is defined in setup(), so data and methods are no longer needed here.
💡 Choosing Between ref and reactive
Both APIs declare reactive data, but their behavior and use cases differ.
- ref wraps primitive values (strings, numbers, and booleans) as well as objects. Access the wrapped value through .value.
- reactive makes an object reactive. Access its properties directly, without .value.
Example:
import { ref, reactive } from 'vue';
const count = ref(0); // Primitive value: access through count.value
const state = reactive({ name: 'Zhang San', age: 18 }); // Object: access through state.name
However, reactive cannot wrap primitive values directly:
const num = reactive(0); // Incorrect usage
🕰 Lifecycle Hooks in setup() (onMounted and Others)
Vue 2 uses lifecycle options such as created, mounted, and updated. The Composition API exposes standalone functions such as onMounted and onUpdated instead.
Example:
import { onMounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log('Component mounted');
});
},
};
This lets us register the appropriate hooks inside setup() and keep related logic together.
🧮 Using computed and watch
computed and watch are also reactivity APIs, with largely familiar usage.
Use computed to declare a computed property:
import { ref, computed } from 'vue';
const firstName = ref('Zhang');
const lastName = ref('San');
const fullName = computed(() => {
return firstName.value + lastName.value;
});
Use watch to observe reactive data and run side effects when it changes:
import { ref, watch } from 'vue';
const count = ref(0);
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
💭 Thinking Beyond this
In Vue 2, this provides access to component data and methods. This is convenient, but its scope can be confusing.
In the Composition API, setup() has no component this context. Access variables directly by name to avoid confusion about what this refers to.
This calls for a different way of thinking:
- Work directly with variables and functions rather than this.
- Organize component state as reactive variables, just as you would organize ordinary JavaScript code.
- Templates still access variables by name, without relying on a this context in your setup code.
For example:
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
},
};
Without this, the code resembles standalone functions and is easier to test and maintain.
✨ The script setup Syntax
Vue 3 introduces script setup as a more concise alternative to a traditional setup() function. It reduces boilerplate between template and logic, keeping code shorter and improving the development experience.
With a traditional setup(), you must explicitly return every variable and function used by the template, which is verbose and easy to get wrong. With script setup, all top-level declarations are automatically available to the template without an explicit return.
Here is an example:
<template>
<button @click="increment">Count: {{ count }}</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
</script>
No return is needed: the variables and functions are directly available, keeping the code concise and helping you work faster.
📦 Using defineProps and defineEmits
script setup provides two compiler macros: defineProps and defineEmits.
They declare a component's props and emitted events and provide bindings you can use in your code.
Using defineProps
<template>
<h1>{{ props.title }} - {{ props.count }}</h1>
</template>
<script setup>
const props = defineProps({
title: String,
count: {
type: Number,
default: 0,
},
});
</script>
Using defineEmits
<template>
<button @click="handleChange">Change</button>
</template>
<script setup>
const emit = defineEmits(['change']);
function handleChange() {
emit('change', 'value');
}
</script>
The emit function emits events, accepting an event name and any arguments.
❓ Questions and Answers
Q1: Why does the Composition API avoid this?
Avoiding this removes ambiguity about scope and makes code resemble ordinary JavaScript, which is easier to understand and test.
Q2: What is the main difference between ref and reactive?
ref can wrap primitives, accessed through .value; reactive wraps objects, whose properties are accessed directly.
Q3: How do you use lifecycle hooks in setup()?
Call the corresponding hook function, such as onMounted(() => {...}), during setup().
🧪 Exercises
Exercise 1
Build a counter component with the Composition API. Support incrementing and decrementing, and log a message whenever the count changes.
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="decrement">Decrement</button>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
const count = ref(0);
// Implement decrement and increment
// Watch count and log changes
</script>
Exercise 2
Write a component that uses reactive to define a user object with name and age properties, then uses computed to generate a description of the user.
<template>
<div>
<p>User information: {{ userInfo }}</p>
</div>
</template>
<script setup>
import { reactive, computed } from 'vue';
const user = reactive({
name: 'Li Si',
age: 20,
});
// Define the computed property userInfo, for example: Li Si, 20 years old
</script>
🎉 You now know the core Composition API skills for writing Vue 3 components with clearer logic and better maintainability! Keep practicing to build your confidence with Vue 3.
Vue 3 Overview and Ecosystem Updates
Explore the core changes in Vue 3 and its ecosystem, and get started with Vue 3 development.
Reusing Composition API Logic
Learn to extract Vue 3 Composition API logic with composables, use provide/inject, encapsulate reactive modules, and avoid common pitfalls while debugging.
