What is Slot in Vue: Simple Explanation and Example
slot is a placeholder inside a component that lets you pass content from a parent component to be displayed inside the child component. It helps you create flexible and reusable components by allowing dynamic content insertion.How It Works
Think of a slot in Vue like a blank space or a window in a reusable box (component) where you can put anything you want from outside. When you use a component, you can fill this blank space with your own content, and the component will show it exactly where the slot is placed.
This works by the parent component sending content to the child component’s slot. The child component defines where the slot is, and Vue replaces the slot with the content you provide. This makes components very flexible because the same component can show different content depending on what you pass into its slots.
Example
This example shows a simple BaseCard component with a default slot. The parent uses BaseCard and passes some text inside it. The card displays that text inside its slot.
<!-- ParentComponent.vue -->
<template>
<BaseCard>
<p>This is content passed into the slot!</p>
</BaseCard>
</template>
<script setup>
import BaseCard from './BaseCard.vue'
</script>
<!-- BaseCard.vue -->
<template>
<div class="card">
<slot></slot>
</div>
</template>
<style>
.card {
border: 1px solid #ccc;
padding: 1rem;
border-radius: 0.5rem;
max-width: 300px;
}
</style>When to Use
Use slots when you want to build components that can show different content depending on where they are used. For example, a modal window component can use slots to display any message or form inside it. A list component can use slots to customize how each item looks.
Slots help keep your components clean and reusable by separating structure from content. Instead of making many similar components, you make one flexible component and pass different content through slots.
Key Points
- Slots are placeholders inside components for dynamic content.
- They allow parent components to pass HTML or other components into child components.
- Default slots show content if no named slot is used.
- Named slots let you define multiple slots with different purposes.
- Scoped slots provide data from child to parent for more control.