Slots and Component Composition
Veeg om het menu te tonen
Reusable components often need flexible content that changes depending on where the component is used. Instead of hardcoding all content directly inside a component, Svelte allows developers to insert custom content using slots.
Slots make components more flexible and easier to reuse in larger applications.
What Are Slots?
A slot is a placeholder inside a component where parent components can insert custom content.
This allows the same component structure to display different content in different situations.
Creating a Component with a Slot
Create a file called Card.svelte.
<div class="card">
<slot></slot>
</div>
<style>
.card {
padding: 20px;
border-radius: 12px;
background-color: #f3f4f6;
}
</style>
The <slot> element acts as a content placeholder.
Passing Content into the Slot
Open App.svelte and use the component:
<script>
import Card from './Card.svelte';
</script>
<Card>
<h2>Welcome</h2>
<p>This content comes from the parent component.</p>
</Card>
The content placed between the opening and closing component tags appears inside the slot.
Why Slots Are Useful
Slots make components much more flexible.
For example, the same card component could display:
- User profiles;
- Product information;
- Notifications;
- Settings panels;
- Dashboard widgets.
The structure stays reusable while the content changes dynamically.
Component Composition
Using components together to build larger interfaces is called component composition.
Instead of creating one massive component, developers combine smaller reusable components into larger application structures.
This approach helps frontend applications remain organized and scalable.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.