Vue — Slots
Default slot
<!-- Card.vue -->
<template>
<div class="card">
<slot></slot>
</div>
</template>
<!-- Usage -->
<template>
<Card>
<p>This goes inside the slot</p>
</Card>
</template>
Named slots
<!-- Card.vue -->
<template>
<div class="card">
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<footer><slot name="footer"></slot></footer>
</div>
</template>
<!-- Usage -->
<template>
<Card>
<template #header>
<h1>Title</h1>
</template>
<p>Body content</p>
<template #footer>
<button>Submit</button>
</template>
</Card>
</template>
Fallback content
<!-- Button.vue -->
<template>
<button>
<slot>Click me</slot>
</button>
</template>
<!-- Usage -->
<template>
<Button>Custom text</Button>
<Button></Button> <!-- Shows "Click me" -->
</template>
Scoped slots
<!-- List.vue -->
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot :item="item"></slot>
</li>
</ul>
</template>
<script>
export default {
props: ['items']
}
</script>
<!-- Usage -->
<template>
<List :items="items">
<template #default="{ item }">
<span>{{ item.name }}</span>
</template>
</List>
</template>
Destructuring scoped slots
<template>
<List :items="items">
<template #default="{ item, index }">
<span>{{ index }}. {{ item.name }}</span>
</template>
</List>
</template>
Mini Practice
- Create a card with default slot
- Add named slots for header/footer
- Use scoped slots with v-for
- Add fallback content
Up Next
Continue with Lifecycle - Component hooks.
Related Topics
Frequently Asked Questions about Slots
What is Slots in Vue?
Slots is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Slots?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Slots.
Why is Slots important in Vue?
Slots is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.