How to Use Scoped Slot in Vue: Syntax and Example
In Vue, a
scoped slot lets a child component pass data to the parent through a slot. You define the slot with a v-slot directive and access the passed data as slot props inside the parent template.Syntax
A scoped slot is defined in the child component using a <slot> element with a name. The parent uses v-slot to access the slot and receive data as props.
- Child: Defines
<slot name="slotName" :propName="value"></slot>to pass data. - Parent: Uses
<template v-slot:slotName="slotProps">to receive data.
vue
<!-- ChildComponent.vue --> <template> <slot name="custom" :text="message"></slot> </template> <script setup> const message = 'Hello from child' </script>
Example
This example shows a child component passing a message to the parent using a scoped slot. The parent displays the message received from the child.
vue
<!-- ChildComponent.vue --> <template> <slot name="info" :text="message"></slot> </template> <script setup> const message = 'Hello from Child Component' </script> <!-- ParentComponent.vue --> <template> <ChildComponent> <template v-slot:info="slotProps"> <p>Message from child: {{ slotProps.text }}</p> </template> </ChildComponent> </template> <script setup> import ChildComponent from './ChildComponent.vue' </script>
Output
<p>Message from child: Hello from Child Component</p>
Common Pitfalls
- Forgetting to use
v-sloton a<template>tag in the parent causes the slot props to be unavailable. - Using the wrong slot name or missing the colon
:before prop names in the child breaks data passing. - Trying to access slot props directly on the child tag instead of inside the
<template v-slot>block will not work.
vue
<!-- Wrong usage in parent (no v-slot) -->
<ChildComponent>
<p>{{ text }}</p> <!-- 'text' is undefined here -->
</ChildComponent>
<!-- Correct usage -->
<ChildComponent>
<template v-slot:info="slotProps">
<p>{{ slotProps.text }}</p>
</template>
</ChildComponent>Quick Reference
| Concept | Usage |
|---|---|
| Child slot definition | |
| Parent slot usage | {{ slotProps.prop }} |
| Default slot | |
| Named slot | |
| Scoped slot | Pass data with :prop="value" and receive with v-slot:name="slotProps" |
Key Takeaways
Use
v-slot on a <template> in the parent to access scoped slot props.Pass data from child to parent by binding props on the
<slot> element with : syntax.Always match the slot name between child
name and parent v-slot.Scoped slots let parents customize child content using data the child provides.
Avoid accessing slot props outside the
v-slot template block.