Vue Composition API
Until now most examples used the Options API: you fill in data, methods, computed and watch, and Vue wires them together through this. The Composition API is a second way to write components. Instead of options, you write a setup() function that creates reactive state with functions such as ref() and reactive(), and returns what the template needs.
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
const increment = () => count.value++;
return { count, increment }; // available in the template
}
};Why a second API?
| Options API | Composition API | |
|---|---|---|
| Code organised by | Option type (all data together, all methods together…) | Feature — state, logic and watchers of one feature side by side |
| Reusing logic | Mixins (name clashes, unclear origin) | Composables — plain functions |
this |
Everywhere | Not used |
| TypeScript | Works, but needs help | Excellent type inference |
| Best for | Small components, beginners | Medium/large components, shared logic, libraries |
Both are first-class in Vue 3, and the Options API is itself implemented on top of the Composition API.
ref(): reactive single values
ref(initial) wraps a value in a reactive object with a .value property. In JavaScript you read and write .value; in the template Vue unwraps it automatically, so you just write {{ count }}.
<div id="app">
<p>{{ name }} scored {{ score }} points.</p>
<button @click="score += 10">+10</button>
<button @click="rename">Rename</button>
</div>
<script type="module">
import { createApp, ref } from 'vue';
createApp({
setup() {
const name = ref('Lan');
const score = ref(0);
function rename() {
name.value = name.value === 'Lan' ? 'Phuc' : 'Lan'; // .value in JavaScript
console.log('name is now', name.value, '| score', score.value);
}
return { name, score, rename };
}
}).mount('#app');
</script>A ref can hold anything: numbers, strings, arrays, objects. Objects inside a ref are made deeply reactive.
reactive(): reactive objects
reactive(obj) returns a reactive proxy of an object. You access its properties directly — no .value.
<div id="app">
<p>{{ cart.items.length }} item(s), total ${{ cart.total.toFixed(2) }}</p>
<button v-for="p in products" :key="p.name" @click="addItem(p)">Add {{ p.name }}</button>
<ul><li v-for="(item, i) in cart.items" :key="i">{{ item.name }} — ${{ item.price }}</li></ul>
</div>
<script type="module">
import { createApp, reactive } from 'vue';
createApp({
setup() {
const products = [{ name: 'Tea', price: 3.2 }, { name: 'Cake', price: 4.5 }];
const cart = reactive({ items: [], total: 0 });
function addItem(p) {
cart.items.push(p); // no .value needed
cart.total += p.price;
}
return { products, cart, addItem };
}
}).mount('#app');
</script>ref vs reactive
ref() |
reactive() |
|
|---|---|---|
| Holds | Any value | Objects, arrays, Maps, Sets only |
| Access in JS | x.value |
obj.prop |
| Replace the whole value | ✅ x.value = newObj |
❌ reassigning the variable breaks reactivity |
| Destructuring | Pass the ref around safely | ❌ loses reactivity (use toRefs) |
Tip: The Vue docs recommend
ref()as the default choice. It works for every type and can be replaced as a whole, which avoids the destructuring pitfall below.
The destructuring pitfall
Destructuring a reactive object copies plain values out of it, so the copies no longer update. toRefs() turns each property into a ref that stays linked to the original:
<div id="app">
<p>Original: {{ user.age }} | destructured copy: {{ ageCopy }} | toRefs: {{ age }}</p>
<button @click="user.age++">Birthday 🎂</button>
</div>
<script type="module">
import { createApp, reactive, toRefs } from 'vue';
createApp({
setup() {
const user = reactive({ name: 'Bich', age: 30 });
const { age: ageCopy } = user; // ❌ plain number, frozen at 30
const { age } = toRefs(user); // ✅ ref linked to user.age
return { user, ageCopy, age };
}
}).mount('#app');
</script>Ref unwrapping rules
- In templates, refs returned at the top level of
setup()are unwrapped:{{ count }}. - A ref nested inside a plain object is not unwrapped in the template:
{ counter: { n: ref(1) } }needs{{ counter.n.value }}. - A ref stored as a property of a
reactive()object is unwrapped:state.countinstead ofstate.count.value. - Inside arrays and Maps refs are not unwrapped.
setup() details
setup(props, context) runs before the component is created, so this is undefined in it.
| Parameter | Contains |
|---|---|
props |
Reactive props object (don't destructure without toRefs) |
context.emit |
Emit events |
context.attrs |
Fallthrough attributes |
context.slots |
Slot functions |
context.expose |
Choose what a parent can access through a template ref |
Lifecycle hooks become imported functions (onMounted, onUnmounted, …) called inside setup(), as you saw in the Lifecycle Hooks lesson.
Note: In real projects you'll rarely write
setup()by hand: Single-File Components use<script setup>, where every top-level variable is automatically available in the template. You'll meet it two lessons from now.
Test yourself
Inside setup(), how do you increase const count = ref(0)?
count++count.value++this.count++count.set(count + 1)
What happens if you destructure const { x } = reactive({ x: 1 })?
xstays reactivexis a plain value that won't update- Vue throws an error
xbecomes a ref
What is this inside setup()?
- The component instance
- The app
undefined- The window