Since the first lesson you have been using ref with a rule learnt by heart: "in the script you write .value; in the template, you don't". In this lesson you will understand why. Reactivity is the heart of Vue: it is the mechanism that makes the screen update itself when a piece of data changes. Knowing how it works under the hood is not an academic exercise: it explains the most common mistakes made by developers new to Vue (losing reactivity when destructuring, reassigning a reactive object, forgetting .value) and will let you choose between ref and reactive with sound judgement. We will apply it by moving Colmena's room catalogue into its own data file and organising the state of App.vue.
Contents
- What reactivity is and why JavaScript does not have it built in
- How it works under the hood: Proxy, tracking and triggering
refand.value- Automatic ref unwrapping
reactiveand its limitationstoRefsandtoRef: destructuring without losing reactivity- Deep reactivity versus
shallowRefandshallowReactive readonly: read-only statenextTickand batched DOM updatesrefversusreactive: which one to use- Case study: the room catalogue and the state of
App.vue
- What reactivity is and why JavaScript does not have it built in
Think of a spreadsheet: if cell C1 contains the formula =A1 * B1, changing A1 makes C1 recalculate itself. That is reactivity: the result reacts to changes in its source data.
JavaScript on its own does not work like that:
let capacity = 8
let attendees = 3
let freeSeats = capacity - attendees // 5
attendees = 6
console.log(freeSeats) // still 5: nobody has recalculated itfreeSeats was calculated once and kept that value. For it to update, something would have to know that it depends on attendees and run the calculation again whenever attendees changes. That is exactly what Vue's reactivity system does with each component's render function: it remembers which data it read while rendering and runs it again when any of that data changes.
To achieve this, Vue needs two capabilities that an ordinary variable lacks:
- Knowing when a piece of data is read (to note down who depends on it).
- Knowing when a piece of data is modified (to notify whoever depends on it).
A let variable notifies nobody of anything. That is why reactive data has to be special objects: the ones created by ref and reactive.
- How it works under the hood: Proxy, tracking and triggering
2.1 JavaScript's Proxy
Vue 3 relies on a standard JavaScript feature: the Proxy object. A proxy wraps another object and lets you intercept the operations performed on it, such as reading (get) or writing (set) a property:
const room = { name: 'Panal Room', capacity: 8 }
const watchedRoom = new Proxy(room, {
get(target, key) {
console.log(`Reading ${key}`)
return target[key]
},
set(target, key, value) {
console.log(`Writing ${key} = ${value}`)
target[key] = value
return true // signals that the write succeeded
}
})
watchedRoom.capacity // console: "Reading capacity"
watchedRoom.capacity = 10 // console: "Writing capacity = 10"new Proxy(object, handler)creates the wrapper. The original object still exists; the proxy is a separate reference that goes through the handler's "traps" (get,set).- The traps receive the original object (
target) and the property (key), and decide what to do.
2.2 Tracking (track) and triggering (trigger)
With those traps, Vue implements two operations:
- Tracking (track): in the
gettrap, if an effect is running at that moment (for example, a component's render function), Vue notes down: "this effect depends on this property of this object". - Triggering (trigger): in the
settrap, Vue looks up all the effects that depended on that property and schedules them to run again.
A very simplified version (with our own names; Vue's are track, trigger and effect) would be:
let activeEffect = null
const dependencies = new WeakMap() // object -> Map(key -> Set of effects)
function record(object, key) {
if (!activeEffect) return // nobody is "listening": nothing to note down
let byKey = dependencies.get(object)
if (!byKey) dependencies.set(object, (byKey = new Map()))
let effects = byKey.get(key)
if (!effects) byKey.set(key, (effects = new Set()))
effects.add(activeEffect)
}
function notify(object, key) {
const effects = dependencies.get(object)?.get(key)
effects?.forEach((effect) => effect())
}
function makeReactive(object) {
return new Proxy(object, {
get(target, key) {
record(target, key)
return target[key]
},
set(target, key, value) {
target[key] = value
notify(target, key)
return true
}
})
}
function runEffect(fn) {
const run = () => {
activeEffect = run
fn()
activeEffect = null
}
run()
}
// Usage
const state = makeReactive({ capacity: 8, attendees: 3 })
runEffect(() => {
console.log('Free seats:', state.capacity - state.attendees)
})
// console: "Free seats: 5"
state.attendees = 6
// console: "Free seats: 2" (the effect has run again by itself)You do not have to write any of this: it is the idea of what Vue does for you. What matters is the cycle:
sequenceDiagram
participant R as Render function (effect)
participant P as Reactive proxy
participant D as Dependency registry
R->>P: reads state.attendees
P->>D: track: the render depends on attendees
Note over R: The DOM is generated with attendees = 3
participant U as Your code
U->>P: state.attendees = 6
P->>D: trigger: who depends on attendees?
D-->>R: the render: schedule a new run
R->>P: reads state.attendees again (6)
Note over R: Vue compares and updates only what changed in the DOM
Two consequences worth committing to memory:
- Only what is read through the proxy is tracked. If you modify the original object (not the proxy), Vue does not find out.
- Dependencies are discovered at runtime, not by analysing the code. If one branch of an
ifdid not run, its data was not tracked on that pass.
ref and .value
ref and .valueA Proxy can only wrap objects. But a great deal of an application's data consists of primitive values: a number of attendees, a search text, a showClock boolean. How do you make a number reactive? By putting it in a box: an object with a single property, value, whose accesses can be intercepted. That is a ref:
// Simplified idea of ref (Vue uses a class, but the principle is this)
function makeRef(initialValue) {
let current = initialValue
const box = {
get value() {
record(box, 'value')
return current
},
set value(newValue) {
current = newValue
notify(box, 'value')
}
}
return box
}Now .value makes complete sense: it is the door through which Vue keeps an eye on the data. Reading attendees.value records the dependency; assigning attendees.value = 4 triggers the update.
<script setup>
import { ref } from 'vue'
const attendees = ref(0) // number
const search = ref('') // string
const showClock = ref(true) // boolean
const room = ref({ id: 'panal', capacity: 8 }) // objects are accepted too
function addAttendee() {
attendees.value++ // in the script, always .value
console.log(room.value.capacity) // the object is inside .value
}
</script>Key facts about ref:
- It accepts any type of value: primitives, objects, arrays,
Map,null... - If the value is an object, it makes it deeply reactive: internally it converts it with
reactive(you will see this in section 5). Soroom.value.capacity = 10is reactive too. - It can be reassigned as a whole:
room.value = { id: 'polen', capacity: 4 }is perfectly valid and reactive, because what is intercepted is the access to.value. - It can be passed to functions without losing reactivity: whoever receives the ref receives the box, not a copy of the value.
- Automatic ref unwrapping
Writing .value everywhere would be tedious, so Vue does it for you in some contexts. This is called unwrapping.
4.1 In the template: only at the top level
In the template, refs declared at the top level of <script setup> are unwrapped automatically:
<script setup>
import { ref } from 'vue'
const attendees = ref(3)
const counters = { bookings: ref(2) } // ordinary object that CONTAINS a ref
</script>
<template>
<p>{{ attendees + 1 }}</p> <!-- 4: attendees is top-level -->
<p>{{ counters.bookings + 1 }}</p> <!-- "[object Object]1": not unwrapped -->
<p>{{ counters.bookings }}</p> <!-- 2: special case, see below -->
</template>attendeesis a top-level variable: in the template it is equivalent toattendees.value.countersis an ordinary object; itsbookingsproperty is a nested ref and is not unwrapped in expressions.counters.bookings + 1operates on the ref object, not on the number.- There is a practical exception: if the interpolation is only that ref (
{{ counters.bookings }}), its value is displayed, because the final conversion to text also unwraps it. But do not rely on this as soon as there is an operation involved.
The fix is simple: either declare the ref at the top level (const { bookings } = counters and use bookings), or make the containing object reactive (next point).
4.2 Inside a reactive object
When a ref is a property of a reactive object, it is unwrapped when that property is accessed, in the script as well:
import { ref, reactive } from 'vue'
const booked = ref(0)
const seats = reactive({ booked }) // we store the ref inside
console.log(seats.booked) // 0, without .value
seats.booked++ // modifies the original ref
console.log(booked.value) // 1: they are still connectedException: refs inside arrays or collections such as Map are not unwrapped (reactive([ref(1)])[0].value still needs .value).
| Where the ref is | Is it unwrapped? |
|---|---|
| Top-level variable, used in the template | Yes |
| Property of an ordinary object, used in a template expression | No |
Property of a reactive object (script and template) |
Yes |
Element of a reactive array or of a Map |
No |
In the script, outside a reactive |
Never: use .value |
reactive and its limitations
reactive and its limitationsreactive turns an object directly into a reactive proxy, with no box and no .value:
import { reactive } from 'vue'
const seats = reactive({ booked: 0, capacity: 8 })
seats.booked++ // reactive, without .value
console.log(seats.capacity) // 8Key points:
- It returns a proxy that is different from the original:
reactive(object) !== object. Only changes made through the proxy are reactive, so always work with whatreactivereturns and forget about the original. - It is deep: nested objects and arrays also become reactive when you access them.
- It is stable: calling
reactivetwice on the same object returns the same proxy, andreactive(proxy)returns the proxy itself.
Its convenience comes at a price: three limitations that cause a lot of bugs.
5.1 It does not accept primitives
A number is not an object and cannot be wrapped in a Proxy. For primitives, use ref.
5.2 Reassigning the variable loses reactivity
The template (and any effect) is connected to the original proxy. When you reassign the variable, your code points to a new proxy, but the template is still looking at the old one, which nobody modifies any more. The screen stops updating without any error. The correct approach is to modify properties, not replace the object:
const seats = reactive({ booked: 0 }) // const: this way you cannot even reassign it
function reset() {
seats.booked = 0
// or, for several properties: Object.assign(seats, { booked: 0 })
}5.3 Destructuring loses reactivity
const seats = reactive({ booked: 0, capacity: 8 })
const { booked } = seats // booked is the number 0, with no connection
seats.booked++
console.log(booked) // still 0Destructuring copies the current value into an ordinary variable. The same thing happens when you pass a property to a function: show(seats.booked) passes a number, not something reactive.
toRefs and toRef: destructuring without losing reactivity
toRefs and toRef: destructuring without losing reactivityWhen you need to extract properties from a reactive object while keeping the connection, convert them into refs:
import { reactive, toRefs, toRef } from 'vue'
const seats = reactive({ booked: 0, capacity: 8 })
// toRefs: converts ALL the properties into refs linked to the original
const { booked, capacity } = toRefs(seats)
booked.value++
console.log(seats.booked) // 1: they are connected both ways
// toRef: converts ONE property
const capacityOnly = toRef(seats, 'capacity')
capacityOnly.value = 10
console.log(seats.capacity) // 10toRefs(object)returns an ordinary object whose properties are refs that read from and write to the original. That is why it can be destructured.toRef(object, 'key')creates a ref for a single property.- Since Vue 3.3,
toRefalso accepts a function:toRef(() => seats.booked)creates a read-only ref from a getter.
You will use them mainly when returning state from composables (09-01) and when working with props (03-02).
- Deep reactivity versus
shallowRef and shallowReactive
shallowRef and shallowReactiveBy default, ref and reactive are deep: Vue turns every nested object into a proxy as you access it. This is what you want almost all the time, but it has a cost with huge structures (for example, thousands of records that you are only going to display). For those cases there are shallow versions:
import { shallowRef, shallowReactive, triggerRef } from 'vue'
// shallowRef: only access to .value is reactive, not its contents
const history = shallowRef([]) // imagine 10,000 old bookings
history.value.push({ id: 'r1' }) // does NOT update the view
history.value = [...history.value, { id: 'r2' }] // DOES: .value has been reassigned
triggerRef(history) // manually forces the notification after mutating
// shallowReactive: only the top-level properties are reactive
const preferences = shallowReactive({ theme: 'light', advanced: { timeZone: 'Europe/Madrid' } })
preferences.theme = 'dark' // reactive
preferences.advanced.timeZone = 'UTC' // NOT reactive (it is nested)| Function | What is reactive | When to use it |
|---|---|---|
ref |
.value and all of its contents, deeply |
By default |
shallowRef |
Only the assignment of .value |
Large structures that you replace as a whole (API results, immutable data) or instances of external libraries that must not be wrapped in proxies |
reactive |
Every property, deeply | Grouped state objects |
shallowReactive |
Only the top-level properties | Very specific performance cases |
The shallow versions are an optimisation: do not use them until you need them. We will come back to them in Performance Optimization.
readonly: read-only state
readonly: read-only statereadonly returns a read-only proxy (also deep) of an object or ref. It is still reactive for whoever reads it, but any attempt to write to it is ignored and produces a warning in development:
import { reactive, readonly } from 'vue'
const seats = reactive({ booked: 0 })
const publicSeats = readonly(seats)
publicSeats.booked = 5 // warning: Set operation on key "booked" failed: target is readonly
seats.booked = 5 // fine: the original can be modified
console.log(publicSeats.booked) // 5: it reflects the changes to the originalIts typical use is sharing state without letting others modify it: the owner keeps the original and exposes the readonly version. This pattern will appear when sharing state between components (03-07) and in composables.
nextTick and batched DOM updates
nextTick and batched DOM updatesWhen you modify reactive state, the DOM is not updated at that very instant. Vue collects the changes and updates the DOM only once, at the end of the current "tick" (in a microtask). So if you change ten pieces of data in the same function, the component renders once, not ten times.
Normally you do not notice. But if you need to read the DOM right after changing a piece of data, you will find it has not been updated yet. To wait for Vue to finish, use nextTick:
<script setup>
import { ref, nextTick } from 'vue'
const booked = ref(0)
async function bookSeat() {
booked.value++
const paragraph = document.querySelector('.booked-seats')
console.log(paragraph.textContent) // still the PREVIOUS text
await nextTick() // waits for Vue to apply the changes to the DOM
console.log(paragraph.textContent) // now updated
}
</script>
<template>
<p class="booked-seats">Booked seats: {{ booked }}</p>
<button @click="bookSeat">Book a seat</button>
</template>nextTick()returns a promise that resolves after the next DOM update, which is why we use it withawaitinside anasyncfunction.- Real-world cases: scrolling the page to a newly added element, giving focus to a field that has just appeared, measuring the size of an element after its content changes.
- Here we use
document.querySelectorso as not to get ahead of ourselves; the idiomatic way to access DOM elements is template refs, which you will see in 03-05.
ref versus reactive: which one to use
ref versus reactive: which one to use| Aspect | ref |
reactive |
|---|---|---|
| Accepted types | Any (primitives, objects, arrays...) | Objects only (including arrays, Map, Set) |
| Access in the script | .value |
Direct (seats.booked) |
| Access in the template | Direct (unwrapped at the top level) | Direct |
| Reassigning the whole value | Yes: room.value = otherRoom |
No: you have to modify properties |
| Destructuring | Not applicable (you pass the box) | Loses reactivity; requires toRefs |
| Passing to functions or composables | Keeps reactivity | Keeps reactivity if you pass the whole object, not its properties |
| Visual cue in the code | .value makes it clear that it is reactive |
Indistinguishable from an ordinary object |
Recommendation (that of the official documentation and of this course): use ref by default. It works with any type, it can be reassigned and its .value makes it visible what is reactive. Keep reactive for groups of data that always go together and are never replaced as a whole, such as the state of a form, and always declare it with const.
- Case study: the room catalogue and the state of
App.vue
App.vue11.1 Creating src/data/rooms.js
Until now, the Panal Room's data was written inside RoomCard.vue, and App.vue only knew a standalone number (5). It is time to have a single source of data with the five rooms in the catalogue. Create the src/data/ folder and, inside it, the rooms.js file:
// src/data/rooms.js
// Local catalogue of Colmena rooms (fictitious data).
// Later on, this data will come from a simulated API (lesson 02-05).
export const rooms = [
{
id: 'panal',
name: 'Panal Room',
floor: 1,
capacity: 8,
hourlyPrice: 25,
equipment: ['projector', 'whiteboard'],
available: true
},
{
id: 'polen',
name: 'Polen Room',
floor: 1,
capacity: 4,
hourlyPrice: 15,
equipment: ['screen'],
available: true
},
{
id: 'nectar',
name: 'Néctar Room',
floor: 2,
capacity: 12,
hourlyPrice: 35,
equipment: ['projector', 'whiteboard', 'videoconference'],
available: true
},
{
id: 'enjambre',
name: 'Enjambre Auditorium',
floor: 3,
capacity: 40,
hourlyPrice: 90,
equipment: ['projector', 'microphone', 'videoconference'],
available: false // under maintenance
},
{
id: 'celda',
name: 'Celda Booth',
floor: 2,
capacity: 1,
hourlyPrice: 6,
equipment: ['videoconference'],
available: true
}
]- It is an ordinary JavaScript module: it exports an array of objects following the course's room model (
id,name,floor,capacity,hourlyPrice,equipment,available). - It is not reactive, and it should not be here: this file only describes data. Each component decides which part it needs to be reactive.
- The Enjambre Auditorium is marked as unavailable; it will help us practise states in the coming lessons.
11.2 RoomCard reads the room from the catalogue
In src/components/RoomCard.vue, replace the hand-written room object with a lookup in the catalogue:
import { ref, computed, watch, onMounted } from 'vue'
import { rooms } from '@/data/rooms.js'
// The card still shows the Panal Room (in module 3 it will receive it from outside)
const room = rooms.find((r) => r.id === 'panal')@/data/rooms.js: the@alias points tosrc/, as you saw in 01-03.roomis still not reactive: the card does not modify the room, only itsattendees, which were already aref.
11.3 The state of App.vue with ref and reactive
Now App.vue is going to manage a selected room that the user can change and the booked seats in it. Modify src/App.vue:
<script setup>
import { ref, reactive } from 'vue'
import ReceptionClock from './components/ReceptionClock.vue'
import RoomCard from './components/RoomCard.vue'
import { rooms } from './data/rooms.js'
// Data that does not change
const totalRooms = rooms.length
const today = new Date()
const receptionNote = 'The <strong>Néctar Room</strong> closes at 18:00 today.'
// Reactive state for the header
const freeRooms = ref(rooms.filter((room) => room.available).length)
const showClock = ref(true)
// --- Selected room ---
// ref: it is an object that we are going to REPLACE as a whole when changing room
const selectedRoom = ref(rooms[0])
// reactive: a group of booking data that we modify property by property
const seats = reactive({ booked: 0 })
function nextRoom() {
const index = rooms.findIndex((room) => room.id === selectedRoom.value.id)
selectedRoom.value = rooms[(index + 1) % rooms.length]
seats.booked = 0 // new room: start from zero (without reassigning seats)
}
function bookSeat() {
if (seats.booked < selectedRoom.value.capacity) {
seats.booked++
}
}
function formatDate(date) {
return date.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })
}
function bookRoom() {
if (freeRooms.value > 0) {
freeRooms.value--
}
}
function toggleClock() {
showClock.value = !showClock.value
}
</script>
<template>
<header class="header">
<!-- ... unchanged ... -->
</header>
<main class="content">
<p class="note" v-html="receptionNote"></p>
<p>
<strong>{{ freeRooms }}</strong>
{{ freeRooms === 1 ? 'free room' : 'free rooms' }} out of {{ totalRooms }}
</p>
<button class="button" @click="bookRoom">Book a room</button>
<button class="button" @click="toggleClock">Show/hide clock</button>
<section class="selection">
<h2>Selected room: {{ selectedRoom.name }}</h2>
<p>Floor {{ selectedRoom.floor }} · up to {{ selectedRoom.capacity }} people</p>
<p>Booked seats: {{ seats.booked }} / {{ selectedRoom.capacity }}</p>
<button class="button" @click="bookSeat">Book a seat</button>
<button class="button" @click="nextRoom">Next room</button>
</section>
<RoomCard />
</main>
</template>Let's analyse the decisions:
freeRoomsno longer starts at a hand-written 5: it is calculated from the catalogue (4, because the auditorium is unavailable). It is arefbecause it is a number.selectedRoom = ref(rooms[0]): we userefbecause when "Next room" is clicked we replace the whole object (selectedRoom.value = rooms[...]). Withreactivethat would be impossible without losing reactivity (section 5.2).seats = reactive({ booked: 0 }): a small group of data for the booking in progress that we only modify property by property (seats.booked++,seats.booked = 0). This is a legitimate case forreactive; in the forms lesson we will add more fields to this kind of object.- In the script we write
selectedRoom.value.capacity(ref →.value) butseats.booked(reactive → direct). In the template, both are used without.value. nextRoomfinds the position of the current room and moves to the next one; the%(remainder) operator makes it go back to the first after the last.
Try the application: book a few seats, change room and watch how the counter resets and how you cannot exceed the capacity (in the Celda Booth, only 1 seat). In Vue DevTools, select App: you will see selectedRoom marked as Ref and seats as Reactive.
App.vuenow has both the old "Book a room" button and the new "Book a seat" one. We will tidy this up in the Event Handling lesson.
Common Mistakes and Tips
- Forgetting
.valuein the script.if (attendees > 0)compares a ref object with a number and always givesfalse. ESLint and the "Vue (Official)" extension will usually warn you. - Writing
.valuein the template.{{ attendees.value }}on a top-level ref displays nothing: in the template it is already unwrapped. - Reassigning a
reactive.seats = reactive({...})orseats = newDatadisconnects the view. Declarereactiveobjects withconstand modify properties (or useObject.assign). - Destructuring a
reactive.const { booked } = seatsfreezes the value. UsetoRefs(seats)or access it asseats.booked. - Modifying the original object instead of the proxy. If you do
const data = {...}; const state = reactive(data)and thendata.x = 1, the view does not find out. Always work with the proxy. - Making reactive what does not change. The data in
src/data/rooms.jsor constants such astotalRoomsdo not needref. - Tip: the objects in
src/data/rooms.jsare shared by every module that imports them. If you store them in arefand modify them (selectedRoom.value.available = false), you will be changing the catalogue for the whole application. When a room needs to be edited, work with a copy (we will do it that way with the simulated API).
Exercises
Exercise 1. This code is meant to reset the seat counter when a button is clicked, but the screen does not change. Explain why and fix it in two different ways.
Exercise 2. Predict what the console shows for each console.log and justify your answer:
import { reactive, toRefs, ref } from 'vue'
const seats = reactive({ booked: 1, capacity: 8 })
const { booked } = seats
const { capacity } = toRefs(seats)
seats.booked = 5
seats.capacity = 12
console.log(booked) // (a)
console.log(capacity.value) // (b)
const total = ref(0)
const summary = reactive({ total })
summary.total = 7
console.log(total.value) // (c)Exercise 3. Add a "Previous room" button to the "Selected room" section of App.vue, with its previousRoom() function, so that from the first room it moves to the last. Then, without changing anything else, write the text of the <h2> to the console just before and just after Vue updates the DOM.
Solutions
Solution 1. When seats is reassigned, the variable points to a new proxy, but the template is still connected to the previous proxy, which nobody modifies any more. Fix:
// Option A: modify the property of the original reactive (and declare it with const)
const seats = reactive({ booked: 3 })
function resetSeats() {
seats.booked = 0
}// Option B: use a ref, which does allow its value to be reassigned
const seats = ref({ booked: 3 })
function resetSeats() {
seats.value = { booked: 0 }
}Option A is the idiomatic one if seats makes sense as a group of data; option B, if you need to replace the whole object often. In option B, the template would still use seats.booked.
Solution 2.
- (a)
1: direct destructuring copied the value at that moment; the later change does not affect it. - (b)
12:toRefscreated a ref linked to the reactive'scapacityproperty, so it reflects the change. - (c)
7: thetotalref is inside areactive, where it is unwrapped; whensummary.total = 7is assigned, Vue writes to the original ref's.value.
Solution 3.
import { ref, reactive, nextTick } from 'vue'
async function previousRoom() {
const index = rooms.findIndex((room) => room.id === selectedRoom.value.id)
// We add rooms.length before taking the remainder to avoid a negative index
selectedRoom.value = rooms[(index - 1 + rooms.length) % rooms.length]
seats.booked = 0
const title = document.querySelector('.selection h2')
console.log('Before:', title.textContent)
await nextTick()
console.log('After:', title.textContent)
}- From the first room (index 0):
(0 - 1 + 5) % 5 = 4, the last one. Without addingrooms.length,-1 % 5is-1in JavaScript androoms[-1]isundefined. - "Before" shows the name of the previous room because Vue has not updated the DOM yet; after
await nextTick(), the new one. - Frequent mistake: forgetting to declare the function as
async;awaitcan only be used inside asynchronous functions.
Conclusion
Vue's reactivity is based on intercepting reads and writes: reactive objects are proxies that, when read inside an effect such as the render function, record the dependency (track), and when modified trigger the affected effects again (trigger). ref wraps any value in a box whose .value is the watched door, is unwrapped at the top level of the template and allows reassignment; reactive makes an object reactive without .value, but does not accept primitives and loses the connection if it is reassigned or destructured (that is what toRefs and toRef are for). You also know the shallow variants, readonly and nextTick, which waits for Vue to apply its batched updates. The course's recommendation is clear: ref by default and reactive for groups of data that are never replaced as a whole. Colmena Bookings now has its room catalogue in src/data/rooms.js, and a reactive selectedRoom and seats in App.vue.
The state is now reactive, but in the template we have only displayed it as text. In the next lesson, Data Binding, we will connect it to elements' attributes (images, links, disabled buttons) and take the first step towards two-way binding with a search box.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
