In the previous lesson we extracted the self-sufficient pieces from App.vue, the ones that do not need to talk to anybody. The rest of the interface does need to: a card has to know which room to show, and when the user selects it, the parent has to find out. Vue handles this communication with two complementary mechanisms: props, with which a parent passes data to a child (like the attributes of an HTML element), and custom events, with which a child notifies its parent that something has happened (like a button's click). Together they form a component's public contract: what it receives and what it communicates. In this lesson you will learn how to declare and validate props, how to read them without losing reactivity, why a child must never modify them and how to emit events carrying data. With all this, RoomCard will at last stop always showing the Panal Room, we will create RoomList and StatusBadge, and Colmena's catalogue will become a list of real cards.

Contents

  1. Props: data from parent to child
  2. Declaring props with defineProps: array and object
  3. Default values and factories for objects and arrays
  4. Validation with validator
  5. Reading props in the script: reactive destructuring
  6. One-way data flow: why props must not be mutated
  7. Prop names, static and dynamic values, and Boolean props
  8. Passing objects: :room versus v-bind="room"
  9. Custom events with defineEmits
  10. Emitting events with data and listening to them
  11. Event naming conventions
  12. Options API equivalents
  13. Case study: StatusBadge, RoomCard and RoomList

  1. Props: data from parent to child

A prop (short for property) is a piece of data that a component declares it can receive from its parent. From the outside it is passed like an attribute; from the inside it is read like a variable:

<!-- Parent: passes the room as an attribute -->
<RoomCard :room="panalRoom" />
<!-- Child (RoomCard.vue): declares that it receives it and uses it -->
<script setup>
const { room } = defineProps(['room'])
</script>

<template>
  <h3>{{ room.name }}</h3>
</template>

Each instance receives its own props: if the parent writes three <RoomCard>s with three different rooms, each card shows its own. And props are reactive: if the parent changes the value it passes, the child updates automatically.

Data flows down as props and notifications travel up as events. This is the arrangement we will have by the end of the lesson:

flowchart TD
    App["App.vue<br/>visibleRooms, selectedRoomId"]
    List["RoomList"]
    Card["RoomCard"]
    App -->|"props: rooms, selected-id"| List
    List -->|"props: room, selected"| Card
    Card -.->|"events: select, book"| List
    List -.->|"events: select, book"| App

  1. Declaring props with defineProps: array and object

In <script setup>, props are declared with defineProps(). It is a compiler macro: you do not need to import it, and the compiler replaces it with the real declaration when it processes the SFC. It accepts two forms.

Array form: just the names. Quick for prototypes, but it documents nothing:

const props = defineProps(['room', 'selected'])

Object form: each prop with its options. This is the one we will always use in Colmena, and the one recommended by the official style guide:

const props = defineProps({
  room: {
    type: Object,      // expected type
    required: true     // the parent must pass it
  },
  selected: {
    type: Boolean,
    default: false     // value if the parent does not pass it
  },
  // Short form: just the type
  title: String
})

The possible types are JavaScript's native constructors (and any class of your own):

type Accepts Example prop in Colmena
String Strings status: 'available'
Number Numbers minCapacity: 4
Boolean true / false selected
Array Arrays rooms
Object Objects room
Function Functions (unusual: events are preferred)
Date, Symbol, a class Instances of that type date: Date
[String, Number] Any of the types in the list An identifier that may be text or a number

If the parent passes a value of the wrong type, or omits a required prop, Vue shows a warning in the console during development:

[Vue warn]: Invalid prop: type check failed for prop "room". Expected Object, got String with value "panal".

Two important points:

  • The checks exist only in development: they are removed from the production build so as not to penalise performance. They are not a security measure, but an aid for catching mistakes early.
  • null and undefined pass the type check in non-required props. That is why you can declare selectedId: String and pass it null without any warnings.

  1. Default values and factories for objects and arrays

A non-required prop that the parent does not pass is undefined, unless you give it a default:

defineProps({
  minCapacity: { type: Number, default: 1 },
  sort: { type: String, default: 'none' },

  // Objects and arrays: the default is a FUNCTION that returns the value
  equipment: { type: Array, default: () => [] },
  specs: { type: Object, default: () => ({ floor: 1 }) }
})

Why a function for objects and arrays? For the same reason we saw with createEmptyForm() in Forms with v-model: if the default value were a single array literal, all the instances would share the same array, and whatever one added the others would see. The function (a factory) creates a new array for each instance. Notice the parentheses in () => ({ floor: 1 }): without them, the braces would be interpreted as the function body, not as an object.

  1. Validation with validator

As well as the type, you can check the value with a validator function, which receives the value and returns true if it is acceptable:

defineProps({
  status: {
    type: String,
    required: true,
    validator: (value) =>
      ['available', 'full', 'unavailable', 'confirmed', 'pending', 'cancelled'].includes(value)
  }
})

If it returns false, Vue warns you in the console: Invalid prop: custom validator check failed for prop "status". Like the type check, it only operates in development.

There is a restriction that surprises people the first time. defineProps cannot use variables declared in the <script setup> itself:

// ❌ Compilation error
const STATUSES = ['available', 'full', 'unavailable']
defineProps({
  status: { type: String, validator: (value) => STATUSES.includes(value) }
})

The compiler hoists the props declaration out of the setup function, because it is part of the component definition, which exists before any instance; and STATUSES only exists inside setup. You have three solutions: write the array inside the validator (which is what we will do), import the constant from another module (imports are accessible) or declare it in an ordinary <script> block.

  1. Reading props in the script: reactive destructuring

In the template, props are used directly by name: {{ room.name }}. In the script there are two ways to read them.

Through the props object, the result of defineProps:

const props = defineProps({ room: { type: Object, required: true } })

const freeSeats = computed(() => props.room.capacity - attendees.value)

props is a reactive object: reading props.room inside a computed property connects it to the prop.

By destructuring (Vue 3.5 or later):

const { room, selected = false } = defineProps({
  room: { type: Object, required: true },
  selected: Boolean
})

const freeSeats = computed(() => room.capacity - attendees.value)

This seems to contradict what you learnt in Reactivity: ref and reactive: destructuring a reactive object breaks reactivity. But defineProps is a macro, and the compiler does some special work: it rewrites every use of room as __props.room. The code you write destructures; the code that runs still reads from the reactive object. That is why freeSeats is recalculated if the parent passes another room. What is more, JavaScript's default value syntax (selected = false) becomes the prop's default. In Colmena we will use destructuring, because it makes the code cleaner.

The compiler's magic has limits you need to know about:

Situation What happens What to do
Using the prop inside computed, watchEffect or the template It works: it is rewritten as __props.room Nothing
watch(room, ...) Compilation error: you would be passing the value, not a reactive source watch(() => room, ...), with a getter
Passing it to a function: calculatePrice(room) The function receives the value at that moment; if the prop changes, the function does not notice Pass a getter, () => room, if the function needs to follow the changes (you will see this with composables in 09-01)
Reassigning it: room = anotherRoom Error: destructured props are constants Never reassign a prop (section 6)
Object or array default value: { equipment = [] } It works without a factory: the compiler generates one for you Nothing

  1. One-way data flow: why props must not be mutated

Props form a one-way data flow: they come down from the parent to the child, never the other way round. When the parent updates a piece of data, the new version flows down to the children; but a child must not modify a prop. If it could, any component in the application could alter its parent's state without the parent knowing, and it would be impossible to tell who changed what.

Vue protects against this: the props object is read-only at the top level. If you try props.selected = true, you will see the warning Attempted to assign to readonly property, and the assignment will have no effect. With destructuring it is an outright error, because they are constants.

Usually, someone who wants to modify a prop is in one of these two situations, and each has its own solution:

Case 1: the prop is just an initial value and the child wants its own copy, which it then changes on its own. Use a local copy with ref:

const { initialAttendees = 0 } = defineProps({ initialAttendees: Number })

// Local copy: the child starts from the value received and then manages it itself
const attendees = ref(initialAttendees)

The copy is taken once, when the instance is created: if the parent later changes initialAttendees, attendees does not notice. That is why the prop's name should say so (initial...).

Case 2: the child needs the value transformed. Use a computed property, which keeps up to date with the prop:

const { room } = defineProps({ room: { type: Object, required: true } })

const shortName = computed(() => room.name.replace(/ (Room|Booth|Auditorium)$/, ''))
// 'Panal Room' → 'Panal'

And what if the child wants the value to change in the parent too? Then it must not touch the prop, but ask the parent with an event (section 9). The parent, which owns the data, decides whether to change it. This is so common that Vue has a shortcut, v-model on components, which you will see in the next lesson.

6.1 The object trap

The read-only protection is shallow. If the prop is an object, nothing stops you from writing room.capacity = 20: Vue does not block it, because the object belongs to the parent and is reactive there. But you would be modifying the parent's state behind its back: in Colmena, you would change the room inside App.vue's catalog, and every part that displays it would change without explanation. The rule is the same for objects and arrays: a child does not modify anything it receives. If it needs a change, it emits an event.

  1. Prop names, static and dynamic values, and Boolean props

7.1 camelCase in JavaScript, kebab-case in the template

Props are declared in camelCase, because they are JavaScript identifiers (selectedId, not selected-id, which would not be a valid variable name). In the parent's template, the convention is to write them in kebab-case, like any HTML attribute:

<!-- In the parent -->
<RoomList :selected-id="selectedRoomId" />
// In RoomList.vue
defineProps({ selectedId: String })

Vue automatically converts selected-id into selectedId. Technically :selectedId would also work in an SFC, but the style guide recommends kebab-case in templates so that they read like HTML.

7.2 Static versus dynamic values

Without v-bind, an attribute's value is always a string. This is a very common mistake with numbers and Booleans:

You write The prop receives Correct for capacity: Number?
capacity="8" '8' (string) No: type warning
:capacity="8" 8 (number) Yes
:capacity="room.capacity" The value of the expression Yes
status="pending" 'pending' Yes, if the prop is a String

The rule: if the value is not a literal string, use :. And remember the same-name shorthand you saw in Data Binding: :room is equivalent to :room="room".

7.3 Boolean props

Props of type Boolean have a special behaviour that mimics HTML's Boolean attributes (disabled, checked):

<RoomCard :room selected />          <!-- selected = true -->
<RoomCard :room :selected="true" />  <!-- selected = true -->
<RoomCard :room :selected="false" /> <!-- selected = false -->
<RoomCard :room />                   <!-- selected = false -->
  • The presence of the attribute without a value means true.
  • Its absence means false, not undefined: Vue automatically turns missing Boolean props into false. That is why writing default: false is redundant, although it makes the intention clear.
  • For a value that changes, use :selected="room.id === selectedId".

  1. Passing objects: :room versus v-bind="room"

There are two ways of passing an object's data to a component, and they produce very different contracts:

<!-- A: the whole object in ONE prop -->
<RoomCard :room="room" />

<!-- B: each property of the object as a SEPARATE prop -->
<RoomCard v-bind="room" />
<!-- equivalent to: :id="room.id" :name="room.name" :floor="room.floor" :capacity=... -->
:room="room" v-bind="room"
Props the child declares One: room: Object One per field: id, name, floor, capacity...
Validation Of the object as a whole Field by field, with precise types
If the data model gains a field The child receives it without changes A new prop has to be declared (otherwise the field ends up as an HTML attribute)
Coupling The child knows the shape of the room object The child only knows loose values: it can be used with data that is not a room
Typical use Domain components that work with a complete entity Generic components that receive simple values

RoomCard is a domain component: its reason for existing is to display a room, it uses almost all of its fields and it must keep working if the model grows. It will receive :room. By contrast, v-bind="object" is very useful for passing a whole group of options to a generic component in one go, as we did with imageAttributes on an <img> in Data Binding.

  1. Custom events with defineEmits

Props carry data down. To communicate something upwards, a child emits an event, and the parent listens to it with v-on (@), exactly as it listens to a click.

Events are declared with the defineEmits macro, which returns the emit function. It also accepts two forms.

Array form:

const emit = defineEmits(['select', 'book'])

function select() {
  emit('select', room.id)
}

Object form with validation: each event is associated with a function that receives the emitted data and returns true if it is valid (or null if you do not want to validate it):

const emit = defineEmits({
  select: (id) => typeof id === 'string',
  book: (payload) => typeof payload.roomId === 'string' && Number.isInteger(payload.attendees),
  close: null // no validation
})

If the validation fails, Vue warns you in the console (Invalid event arguments: event validation failed for event "book"), but the event is emitted anyway: as with props, it is a development aid.

Why declare the events, if $emit would work without declaring them? For three reasons:

  • Documentation: by reading defineEmits you know everything a component can communicate, without searching through the template.
  • Validation in development, as you have just seen.
  • Telling them apart from native events: a @click listened to on a component that does not declare click is applied as a native event on its root element. Declaring them avoids ambiguity; you will look at this in depth in Template Refs and Fallthrough Attributes.

defineEmits, like defineProps, can only be used at the top level of <script setup> (not inside a function), and it cannot use local variables in its declaration either.

  1. Emitting events with data and listening to them

emit receives the name of the event and, optionally, the data that goes with it (the payload):

emit('select', room.id)                                       // a single value
emit('book', { roomId: room.id, attendees: attendees.value }) // an object

Although emit accepts several arguments (emit('book', room.id, attendees.value)), with more than one value it is better to use an object with names: the parent does not depend on the order, and the event can grow without breaking anything.

The parent listens to the event like any other, and can handle it in several ways:

<!-- By name: the function receives the data as arguments -->
<RoomCard :room @select="selectRoom" />

<!-- Inline, with $event: it contains the FIRST value emitted -->
<RoomCard :room @select="selectedRoomId = $event" />

<!-- With an arrow function -->
<RoomCard :room @book="(payload) => prepareBooking(payload)" />

In the child's template you can emit directly with $emit('select', room.id), without going through the script. It is convenient for trivial cases; when there is logic involved, a function in the script is better.

10.1 Component events do not propagate

Unlike DOM events, component events do not bubble: only the direct parent hears them. If RoomCard emits select, App cannot listen to it directly, because RoomList sits between them. The intermediate component must re-emit it:

<!-- RoomList.vue: listens to each card and re-emits towards App -->
<RoomCard
  v-for="room in rooms"
  :key="room.id"
  :room
  @select="emit('select', $event)"
/>

This is deliberate: each component decides which part of what happens inside it forms part of its public contract. When the chain gets very long (five levels forwarding the same thing), it is a sign that you need another tool, such as slots (03-04) or provide/inject (03-07).

sequenceDiagram
    participant U as User
    participant C as RoomCard
    participant L as RoomList
    participant A as App.vue
    U->>C: click on "Select"
    C->>L: emit('select', 'polen')
    L->>A: emit('select', 'polen')
    A->>A: selectedRoomId = 'polen'
    A-->>L: prop selected-id = 'polen'
    L-->>C: prop selected = true

Look at the complete cycle: the child does not mark itself as selected. It requests the selection, the parent changes its state and the new prop comes down. There is a single source of truth, selectedRoomId in App.

  1. Event naming conventions

Convention Example Reason
Emit in camelCase emit('bookingCreated') It is a JavaScript identifier
Listen in kebab-case @booking-created="..." Consistent with the rest of the attributes; Vue converts between the two forms automatically
Names that describe the action or what happened, not the interface select, book, create blueButtonClick breaks when the design changes; book remains true
No native event names Avoid click, input, change for your own events They get mixed up with the native ones (unless you do it deliberately, as in a BaseButton)
The update: prefix is reserved update:modelValue It is the convention for v-model on components (03-03)

In Colmena we will name events with verbs in their base form that express what the child is asking the parent to do: select, book, create. What matters, once again, is to choose a criterion and stick to it.

  1. Options API equivalents

A lot of existing code uses the Options API. The same ideas are expressed like this:

Concept <script setup> Options API
Declaring props defineProps({ room: Object }) props: { room: Object } option
Reading a prop in the script room (destructured) or props.room this.room
Reading a prop in the template room room
Declaring events defineEmits(['select']) emits: ['select'] option
Emitting from the script emit('select', id) this.$emit('select', id)
Emitting from the template $emit('select', id) $emit('select', id)
Local copy of a prop const n = ref(initialValue) data() { return { n: this.initialValue } }
Transforming a prop computed(() => ...) computed: { ... } option
// RoomCard with the Options API (just so you can recognise it)
export default {
  props: {
    room: { type: Object, required: true },
    selected: { type: Boolean, default: false }
  },
  emits: ['select', 'book'],
  methods: {
    select() {
      this.$emit('select', this.room.id)
    }
  }
}

With the explicit setup() function you saw in 01-05, the props arrive as the first parameter and emit in the second: setup(props, { emit }). Be careful: that props cannot be destructured without losing reactivity; reactive destructuring is exclusive to the defineProps macro.

  1. Case study: StatusBadge, RoomCard and RoomList

We are going to deliver what we have been promising since module 1: RoomCard will receive the room it should display. With it we will build RoomList, which will replace the catalogue's list of <li> elements, and we will extract the status badge into its own component.

13.1 StatusBadge.vue

In Class and Style Bindings we created a badge with three statuses inside RoomCard. We are going to extract it into a component that can also be used for the statuses of bookings (confirmed, pending, cancelled). Create src/components/StatusBadge.vue:

<script setup>
const { status } = defineProps({
  status: {
    type: String,
    required: true,
    // Written in here because defineProps cannot use local constants
    validator: (value) =>
      ['available', 'full', 'unavailable', 'confirmed', 'pending', 'cancelled'].includes(
        value
      )
  }
})

const labels = {
  available: 'Available',
  full: 'Full',
  unavailable: 'Unavailable',
  confirmed: 'Confirmed',
  pending: 'Pending',
  cancelled: 'Cancelled'
}
</script>

<template>
  <span class="badge" :class="`badge--${status}`">{{ labels[status] }}</span>
</template>

<style scoped>
.badge {
  display: inline-block;
  padding: 0.1rem 0.6rem;
  border-radius: 999px;
  font-size: 0.8rem;
  font-weight: bold;
  vertical-align: middle;
}

.badge--available,
.badge--confirmed {
  background: #e8f5e9;
  color: #1b5e20;
}

.badge--full,
.badge--pending {
  background: #fff3e0;
  color: #e65100;
}

.badge--unavailable,
.badge--cancelled {
  background: #eeeeee;
  color: #616161;
}
</style>
  • status is required and validated: if someone writes status="free", the console will say so.
  • labels can be a local constant, because it is not used inside defineProps.
  • The badge styles move here from RoomCard (delete them there). The booking statuses reuse the colours of the room statuses with an equivalent meaning.

13.2 RoomCard.vue receives the room

Replace the <script setup> of src/components/RoomCard.vue:

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import StatusBadge from './StatusBadge.vue'

// --- Public contract: what it receives... ---
const { room, selected = false } = defineProps({
  room: {
    type: Object,
    required: true,
    validator: (value) => typeof value.id === 'string' && value.capacity > 0
  },
  selected: Boolean
})

// --- ...and what it communicates ---
const emit = defineEmits({
  select: (id) => typeof id === 'string',
  book: (payload) => typeof payload.roomId === 'string' && Number.isInteger(payload.attendees)
})

// --- Formatting (still duplicated with App.vue until module 7) ---
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })

function formatPrice(amount) {
  return euroFormatter.format(amount)
}

// --- Presentation: these depend on the prop, so they are now computed properties ---
const imageAttributes = computed(() => ({
  src: `/img/rooms/${room.id}.webp`,
  alt: `Photo of the ${room.name}`,
  width: 320,
  height: 180,
  loading: 'lazy'
}))
const floorPlanUrl = computed(() => `/floor-plans/floor-${room.floor}.pdf`)

const floorColors = { 1: '#f5a623', 2: '#43a047', 3: '#5c6bc0' }
const themeColor = computed(() => floorColors[room.floor])

// --- Occupancy: each card's OWN state ---
const attendees = ref(0)
const notice = ref('')

const freeSeats = computed(() => room.capacity - attendees.value)
const full = computed(() => freeSeats.value === 0)
const occupancyPercentage = computed(() =>
  Math.round((attendees.value / room.capacity) * 100)
)

const status = computed(() => {
  if (!room.available) return 'unavailable'
  if (full.value) return 'full'
  return 'available'
})

watch(full, (isFull) => {
  notice.value = isFull
    ? `Room full as of ${new Date().toLocaleTimeString('en-GB')}!`
    : ''
})

function addAttendee() {
  if (!full.value) attendees.value++
}

function removeAttendee() {
  if (attendees.value > 0) attendees.value--
}

// --- Actions communicated to the parent ---
function select() {
  emit('select', room.id)
}

function book() {
  emit('book', { roomId: room.id, attendees: attendees.value })
}

onMounted(() => {
  console.log(`[RoomCard] ${room.name} ready`)
})
</script>

The changes, one by one:

  • Gone are import { rooms } and the line const room = rooms.find(...): the room arrives through props. statusLabels disappears too, as it now lives in StatusBadge.
  • room is required, with a minimal validator of its shape. selected is a Boolean: false unless the parent says otherwise.
  • imageAttributes, floorPlanUrl and themeColor change from constants into computed properties. Before, the room could not change; now it is a prop and, in theory, the parent could pass a different one. A constant calculated when the instance is created would be stuck with the old room: this is case 2 in section 6. v-bind(themeColor) in the CSS works in just the same way with a computed property.
  • attendees is still the card's own state: each room in the catalogue will have its own counter.
  • select() and book() do not change anything on their own: they ask the parent to act. book sends the room and the attendees the user has set on the card.

In the template, change the card's heading and the badge, and add the actions at the end of the <article>:

<template>
  <article
    class="card"
    :class="[`card--${status}`, { 'card--selected': selected }]"
    :id="'room-' + room.id"
    :title="`${room.name}: floor ${room.floor}`"
  >
    <img v-bind="imageAttributes" class="photo" />
    <h3>{{ room.name }}</h3>
    <StatusBadge :status />

    <!-- ... paragraphs, occupancy bar, notice, attendee buttons
         and floor plan link: no changes ... -->

    <div class="card__actions">
      <button class="button" :disabled="selected" @click="select">
        {{ selected ? 'Selected' : 'Select' }}
      </button>
      <button class="button" :disabled="!room.available" @click="book">Book</button>
    </div>
  </article>
</template>
  • The heading changes from <h2> to <h3>: the card will be inside the "Catalogue" section, whose heading is an <h2>. Heading levels should reflect the structure, for accessibility.
  • <StatusBadge :status /> uses the same-name shorthand: it passes the card's status computed property to the badge's status prop.
  • :class combines the status class with card--selected, controlled by the prop.

In the <style scoped>, delete the .badge* rules, remove max-width: 320px from .card (from now on the list's grid will decide the width) and add:

.card--selected {
  outline: 3px solid var(--color-honey-dark);
  outline-offset: 2px;
}

.card__actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 1rem;
}

13.3 RoomList.vue

Create src/components/RoomList.vue:

<script setup>
import RoomCard from './RoomCard.vue'

const { rooms, selectedId = null } = defineProps({
  rooms: { type: Array, required: true },
  selectedId: String
})

const emit = defineEmits(['select', 'book'])
</script>

<template>
  <ul class="room-list">
    <li v-for="room in rooms" :key="room.id">
      <RoomCard
        :room
        :selected="room.id === selectedId"
        @select="emit('select', $event)"
        @book="emit('book', $event)"
      />
    </li>
  </ul>
</template>

<style scoped>
.room-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 1rem;
  padding: 0;
  list-style: none;
}
</style>
  • rooms: the array to be rendered. RoomList does not know whether it comes filtered, sorted or from the API: it just displays it.
  • selectedId: it can be null (none selected); that is why it is not required.
  • :key="room.id" is essential: as you saw in List Rendering, it guarantees that each card's attendees counter travels with its room when filtering or sorting.
  • The events are re-emitted as they are, with $event as the payload, because component events do not propagate on their own.

13.4 App.vue listens and updates the state

With each card showing its own room, the seat management in the "Selected room" section (seats, hours, freeSeats, canBook, estimatedPrice and the functions bookSeats, releaseSeats, onBookClick, cancelSeats and nextRoom) is now duplicated: the attendee counter on each card and the booking form, which already calculates the price, do that job. Delete all those declarations from the script and their buttons from the template. In ShortcutsHelp.vue, also delete the sentence about Shift + click on "Book a seat", whose button no longer exists.

In the script of App.vue, adjust the imports and the room selection:

// Imports: RoomCard is no longer used directly in App
import RoomList from './components/RoomList.vue'
import StatusBadge from './components/StatusBadge.vue'

// --- Selected room (replaces the writable computed property and seats) ---
const selectedRoomId = ref('panal')
const selectedRoom = computed(() =>
  rooms.find((room) => room.id === selectedRoomId.value)
)

function selectRoom(id) {
  selectedRoomId.value = id
}

// Response to a card's "book" event: prepares the form
function prepareBooking({ roomId, attendees }) {
  selectRoom(roomId)
  form.roomId = roomId
  form.attendees = Math.max(1, attendees)
}

And in createEmptyForm(), since seats no longer exists, change the attendees line to attendees: 1.

  • selectedRoomId is a simple ref once again: the rule that justified the writable computed property (resetting the seats when the room changed) has disappeared along with the seats. selectedRoom becomes a computed property derived from the id; since it was also read with .value before, specSheet, roomMatches and the title's watchEffect do not change.
  • prepareBooking receives the object emitted by the card (destructured in the parameters), and App, which owns the state, decides what to do: select the room and fill in the form. Math.max(1, ...) prevents bookings for 0 people if the user did not set any attendees.

In the template, inside the catalogue's <template v-else> branch, replace the whole <ul class="room-list"> list (about 25 lines) with:

<RoomList
  :rooms="visibleRooms"
  :selected-id="selectedRoomId"
  @select="selectRoom"
  @book="prepareBooking"
/>

Replace the .selection section with this version, which no longer contains the seat management:

<section class="selection">
  <h2>
    Selected room: {{ selectedRoom.name }}
    <StatusBadge :status="selectedRoom.available ? 'available' : 'unavailable'" />
  </h2>
  <dl class="spec-sheet">
    <template v-for="(value, key) in specSheet" :key="key">
      <dt>{{ key }}</dt>
      <dd>{{ value }}</dd>
    </template>
  </dl>
  <p v-if="!selectedRoom.available" class="notice">This room is under maintenance.</p>
  <button
    class="button"
    :disabled="!selectedRoom.available"
    @click="prepareBooking({ roomId: selectedRoom.id, attendees: 1 })"
  >
    Book this room
  </button>
</section>

In the list of created bookings, replace <em>{{ booking.status }}</em> with <StatusBadge :status="booking.status" />: the same component now works for rooms and for bookings.

Finally, delete the standalone <RoomCard /> at the end of <main>: the fixed Panal Room no longer makes sense, because each room in the catalogue has its own card. And in the <style scoped> of App.vue, delete the .room-list, .room-list__item* and .equipment* rules, which are no longer used.

13.5 Try it

  1. The catalogue now shows a complete card for each room, with its photo, its floor colour and its occupancy bar. The console shows a [RoomCard] ... ready for each room.
  2. Click "Select" on the Polen Room: its card is highlighted, the button changes to "Selected", and the "Selected room" section and the tab title change. No card has marked itself: App did it by changing selectedRoomId.
  3. Add 3 attendees on the Néctar card and click "Book": the booking form switches to the Néctar Room with 3 attendees.
  4. Sort by price: each card keeps its attendee counter, thanks to the key.
  5. In Vue DevTools, select a RoomCard: you will see its props (room, selected) separately from its state (attendees, notice). In the Timeline tab, in the Component events layer, you will see every select and book emitted.
  6. Check the validation: in RoomList, temporarily change :room to room="panal". The console will show the type warning and then errors when trying to read room.capacity from a string. Undo the change.

Common Mistakes and Tips

  • Passing numbers or Booleans without :. capacity="8" is the string '8'. Use :capacity="8".
  • Modifying a prop in the child. Use a local copy (ref) if it is an initial value, a computed property if it is a transformation, or emit an event if the change has to reach the parent.
  • Mutating the properties of a received object (room.capacity = 10). Vue does not prevent it, but you are altering the parent's state behind its back.
  • Using an array or object literal as the default in the object form. Use a factory: default: () => [].
  • Passing a destructured prop to watch. Use a getter: watch(() => room, ...).
  • Using local constants inside defineProps or defineEmits. Write them inside, import them or declare an ordinary <script>.
  • Expecting an event to reach the grandparent. Component events are only heard by the direct parent; re-emit them.
  • Forgetting to declare an event. It works with $emit, but you lose documentation and validation, and it can get mixed up with native events.
  • Tip: before writing a component, define its contract: which props it receives (with types) and which events it emits (with their data). If the contract is easy to explain, the component is well bounded.

Exercises

Exercise 1. Add a compact prop (Boolean) to RoomCard. When it is true, the card must not show the photo or the floor plan link. Use it from RoomList so that, when there are more than 4 visible rooms, they are all shown compact. What would you write in the tag to activate it always, and what to activate it with the condition?

Exercise 2. This component has three design problems. Find them and fix them.

<script setup>
const props = defineProps({
  rooms: { type: Array, default: [] },
  initialFloor: Number
})

function nextFloor() {
  props.initialFloor = props.initialFloor === 3 ? 1 : props.initialFloor + 1
}
</script>

<template>
  <p>Floor {{ initialFloor }}: {{ rooms.filter((r) => r.floor === initialFloor).length }} rooms</p>
  <button @click="nextFloor">Next floor</button>
</template>

It is used like this in the parent: <FloorSummary :rooms="catalog" initial-floor="1" />.

Exercise 3. Make RoomCard emit a fill event when the room fills up (when full becomes true), with a { roomId, time } object. Declare the event with validation. Make RoomList re-emit it and make App.vue listen to it and store the text "Polen Room full at 10:32:05" in a ref called lastFullRoom, displaying it in the catalogue section.

Solutions

Solution 1.

// RoomCard.vue
const { room, selected = false, compact = false } = defineProps({
  room: { type: Object, required: true, validator: (value) => typeof value.id === 'string' && value.capacity > 0 },
  selected: Boolean,
  compact: Boolean
})
<!-- RoomCard.vue, in the template -->
<img v-if="!compact" v-bind="imageAttributes" class="photo" />
<!-- ... -->
<a v-if="!compact" :href="floorPlanUrl" target="_blank" rel="noopener">Floor {{ room.floor }} plan</a>
<!-- RoomList.vue -->
<RoomCard
  :room
  :selected="room.id === selectedId"
  :compact="rooms.length > 4"
  @select="emit('select', $event)"
  @book="emit('book', $event)"
/>

To activate it always, <RoomCard :room compact /> would be enough: in a Boolean prop, the presence of the attribute is equivalent to true. With a condition, you bind it: :compact="rooms.length > 4".

Solution 2. The problems:

  1. default: []: an array literal shared by all the instances. It must be default: () => [].
  2. Mutating a prop in nextFloor: Vue blocks it with a warning. initialFloor is an initial value, so the component needs a local copy.
  3. initial-floor="1" without : in the parent: the string '1' arrives, the type validation fails and the comparison r.floor === initialFloor (number against string) is never true.
<script setup>
import { ref, computed } from 'vue'

const { rooms = [], initialFloor = 1 } = defineProps({
  rooms: Array,
  initialFloor: Number
})

const floor = ref(initialFloor) // local copy: from here on the component manages it
const roomCount = computed(() => rooms.filter((r) => r.floor === floor.value).length)

function nextFloor() {
  floor.value = floor.value === 3 ? 1 : floor.value + 1
}
</script>

<template>
  <p>Floor {{ floor }}: {{ roomCount }} rooms</p>
  <button @click="nextFloor">Next floor</button>
</template>
<FloorSummary :rooms="catalog" :initial-floor="1" />

With destructuring, rooms = [] does not need a factory: the compiler generates one. In addition, the filter has been moved into a computed property so that it is not recalculated in the template.

Solution 3.

// RoomCard.vue
const emit = defineEmits({
  select: (id) => typeof id === 'string',
  book: (payload) => typeof payload.roomId === 'string' && Number.isInteger(payload.attendees),
  fill: (payload) => typeof payload.roomId === 'string' && typeof payload.time === 'string'
})

watch(full, (isFull) => {
  const time = new Date().toLocaleTimeString('en-GB')
  notice.value = isFull ? `Room full as of ${time}!` : ''
  if (isFull) {
    emit('fill', { roomId: room.id, time })
  }
})
<!-- RoomList.vue: declare 'fill' in defineEmits and re-emit it -->
<RoomCard
  ...
  @fill="emit('fill', $event)"
/>
// App.vue
const lastFullRoom = ref('')

function logFullRoom({ roomId, time }) {
  lastFullRoom.value = `${roomNameById(roomId)} full at ${time}`
}
<RoomList ... @fill="logFullRoom" />
<p v-if="lastFullRoom" class="note">{{ lastFullRoom }}</p>

The watcher that already existed is the natural place to emit from: the event is an effect of a change of state. roomNameById is the function App.vue already had for the list of bookings. Remember to add 'fill' to the defineEmits array in RoomList.

Conclusion

Props are the channel through which a parent passes data to a child: they are declared with defineProps, preferably in object form with type, required, default (with a factory for objects and arrays) and validator, and since Vue 3.5 they can be destructured without losing reactivity, as long as they are passed to watch or to functions as getters. They form a one-way flow: the child never modifies them, but uses a local copy or a computed property, or asks the parent for the change. Custom events are the return channel: they are declared with defineEmits (also with validation), emitted with emit and a data object, and listened to with @, without propagating beyond the direct parent. Colmena has taken a leap forward: RoomCard receives its room and emits select and book, RoomList renders the catalogue and re-emits those events, StatusBadge works for both rooms and bookings, and App.vue is the single source of truth for the selected room. The fixed Panal Room and the duplicated seat management have gone.

Notice, however, a pattern that will come up again and again: for a child to modify a piece of the parent's data, we need a prop to pass it down and an event to request the change. That is exactly what the catalogue filters or the fields of a form need. Vue has a shortcut for this pair, which you already know from <input>s: v-model. In v-model on Your Own Components we will use it to create RoomFilters, TextField and, at last, BookingForm.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved