What is Named Slot in Vue: Explanation and Example
named slot in Vue is a way to define multiple placeholders inside a component where different content can be inserted. Unlike the default slot, named slots let you specify which part of the component the content should fill by giving each slot a unique name.How It Works
Think of a Vue component as a box with several empty compartments. A named slot is like labeling each compartment so you know exactly where to put different items. Instead of putting all content in one place, you can assign content to specific named slots.
When you use a named slot, the parent component sends content tagged with the slot's name. The child component then places that content in the matching slot area. This helps organize complex layouts by clearly separating content sections.
Example
This example shows a Card component with two named slots: header and footer. The parent component fills these slots with different content.
<template> <div class="card"> <header class="card-header"> <slot name="header">Default Header</slot> </header> <main class="card-body"> <slot>Default Body Content</slot> </main> <footer class="card-footer"> <slot name="footer">Default Footer</slot> </footer> </div> </template> <script setup> // No script needed for this example </script> <style scoped> .card { border: 1px solid #ccc; padding: 1rem; border-radius: 0.5rem; max-width: 300px; } .card-header, .card-footer { background: #f0f0f0; padding: 0.5rem; font-weight: bold; } .card-body { padding: 1rem 0; } </style>
When to Use
Use named slots when your component needs multiple distinct areas for content that the parent controls. This is common in UI components like cards, modals, or layouts where you want to separate header, body, and footer content.
Named slots help keep your components flexible and reusable by letting users insert different content in specific places without changing the component's structure.
Key Points
- Named slots let you define multiple content placeholders inside a component.
- Each slot has a unique
nameattribute to identify it. - The parent component uses
v-slot:nameor#namesyntax to provide content for each named slot. - Named slots improve component flexibility and organization.
Key Takeaways
name attribute on slot to create named slots.v-slot:name or shorthand #name.