We use cookies to enhance your experience on the site
CodeWorlds

Slots - Basics

Welcome to the NOVA LAB Module Storage! Here every cargo container has standardized docking ports - you can plug in different content while keeping the same outer structure. In Vue this mechanism is called slots - they allow a parent to inject arbitrary content into a child component.

What is a Slot?

A slot is a place in a child component's template that the parent can fill with its own content. It's like a docking port in a cargo bay - the component defines where the opening is, and the parent decides what to put in it.

1<!-- CargoBay.vue (child) -->
2<template>
3  <div class="cargo-bay">
4    <h2>Cargo Bay Alpha</h2>
5    <div class="content">
6      <slot></slot>
7    </div>
8  </div>
9</template>
10
11<!-- App.vue (parent) -->
12<template>
13  <CargoBay>
14    <p>Oxygen Tank OX-2087</p>
15    <p>Weight: 250 kg</p>
16  </CargoBay>
17</template>

The parent places content between the component's tags, and that content goes where

<slot></slot>
is.

Fallback Content

A slot can have default (fallback) content - it's displayed when the parent doesn't pass anything:

1<!-- CargoBay.vue -->
2<template>
3  <div class="cargo-bay">
4    <slot>
5      <p>Cargo bay empty - awaiting equipment</p>
6    </slot>
7  </div>
8</template>
9
10<!-- Usage without content - displays fallback -->
11<CargoBay />
12
13<!-- Usage with content - replaces fallback -->
14<CargoBay>
15  <p>Water Recycler Unit</p>
16</CargoBay>

Slot Scope

Slot content is compiled in the parent's scope, not the child's. This means you have access to the parent's data:

1<!-- App.vue -->
2<script setup>
3import { ref } from 'vue'
4const moduleName = ref('Oxygen Generator')
5</script>
6
7<template>
8  <CargoBay>
9    <!-- moduleName comes from the PARENT -->
10    <p>{{ moduleName }}</p>
11  </CargoBay>
12</template>

Multiple Elements in a Slot

A slot can accept any number of elements - text, HTML, and even other components:

1<template>
2  <CargoBay>
3    <h3>Critical Equipment</h3>
4    <ul>
5      <li>Oxygen Tank</li>
6      <li>Water Filter</li>
7    </ul>
8    <StatusBadge status="loaded" />
9  </CargoBay>
10</template>
Go to CodeWorlds