Vue js Slots
Introduction to Vue Slots
Slots in Vue serve as content insertion points that allow components to remain generic while receiving dynamic structure from their parents. This capability unlocks layout flexibility, where the outer container is defined by the component, but the inner content is injected as needed.
Component Usage Without Slots
Without slots, you typically pass data through props and use tightly bound markup. This makes it hard to reuse the visual wrapper without repeating inner logic. Slots solve this by letting components wrap user-defined content.
<!-- ParentComponent.vue -->
<container-box>
Display this content inside the styled box!
</container-box>Receiving Data via Tag
To allow such embedded content, the child component must declare a
<!-- ContainerBox.vue -->
<template>
<section class="box">
<slot></slot>
</section>
</template>Basic Example Explained
A parent can provide text, HTML tags, or even entire Vue templates within the opening and closing tags of a component. The
Multiple Cards Using One Wrapper
For instance, let’s say you want to make a visual list of food items. Instead of hardcoding repeated layouts, a single component with a slot can serve as the wrapper.
<!-- Looping dynamic items -->
<container-box v-for="dish in menu">
<img :src="dish.image" />
<h4>{{ dish.title }}</h4>
<p>{{ dish.note }}</p>
</container-box>And the container-box component wraps this all with a shadow or frame without caring what’s inside.
Scoped Styling with Slots
The styling for such wrappers can be done in a scoped style section of the component. This ensures that only the slotted layout receives the styling, without affecting other sections of the page.
<container-box>
<h4>Application Footer</h4>
<small>All rights reserved</small>
</container-box>Fallback Content in Vue Slots
Slots can include backup content. This appears only if no content is sent from the parent. This ensures your component doesn’t break when left empty.
<!-- In the child component -->
<slot>
<p>This shows when no external content is passed.</p>
</slot>Default Content Example
If a parent leaves a slot blank:
<container-box></container-box>
Then the fallback
will render.
Summary
Slots offer component-level flexibility in Vue by decoupling structure and content. They enable dynamic HTML composition, visual consistency, and elegant reuse of layout patterns.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand VUE JS Tutorial visually:
What You'll Learn:
- 📌 Vue JS 3 Tutorial - 37 - Slots
- 📌 Vue Slots Simplified