What Are Slots?
Slots are placeholders in a component’s template where parent components can inject their own content. They enable flexible composition without requiring the child component to know the specifics of what content will be rendered.Creating Slots
UsecreateSlot() to define a slot in your component:
createSlot() is props, and the third argument is default content that will be shown if no content is provided.
Using Components with Slots
When using a component with slots, pass children to fill the default slot:Named Slots
Components can have multiple named slots for different areas:Providing Named Slot Content
UsecreateSlotContent() to target specific named slots:
Content not wrapped in
createSlotContent() automatically goes into the default slot.Complete Slots Example
Here’s a complete example showing slots in action:How Slots Work Internally
When a component with slots is rendered:- Extraction: Children are analyzed to identify slot content using
extractSlotContents() - Storage: Slot contents are stored by name in the component instance
- Resolution: During render,
resolveSlots()replaces slot placeholders with actual content - Fallback: If no content is provided for a slot, the default content is used
Default Slot
If you don’t specify a slot name, it uses the “default” slot:createSlotContent() automatically fills the default slot:
Slots vs. Props
- When to Use Slots
- When to Use Props
- Complex content with markup
- Multiple insertion points
- Parent controls content structure
- Flexible composition
Real-World Patterns
Dialog Component
Layout Component
Tab Component
Best Practices
Provide Default Content
Provide Default Content
Always provide default content for slots so the component works even when no content is provided.
Use Named Slots for Clarity
Use Named Slots for Clarity
When you have multiple slots, use descriptive names to make it clear where content goes.
Document Your Slots
Document Your Slots
Clearly document what slots your component accepts and what content they expect.
Combine with Props
Combine with Props
Use slots for content and props for configuration:
API Reference
createSlot()
Creates a slot placeholder in a component template.name(string, optional): The slot name. Defaults to"default".props(object, optional): Additional properties for the slot.children(array, optional): Default content if no slot content is provided.
createSlotContent()
Creates content targeted at a specific named slot.slotName(string, optional): The target slot name. Defaults to"default".children(array): The content to insert into the slot.
Related
Component Composition
Learn about composing components
Functional Components
Create functional components