Vue Tip: Expose Slots From a Child Component

Michael Hoffmann
Oct 1, 2022
| 1 min read
| 1784 views
Michael Hoffmann
Oct 1, 2022
1 min read
| 1784 views
Template
Slots

Third-party components are often wrapped in a custom component. But in that way, the slots of the third-party component get lost.
The following solution exposes all slots of the third-party component to the parent component:
1
<template>
2
<div class="wrapper">
3
<ThirdPartyComponent v-bind="$attrs">
4
<!-- Expose all slots of the third-party component -->
5
<template v-for="(_, name) in $slots" #[name]="slotProps">
6
<slot :name="name" v-bind="slotProps || {}"></slot>
7
</template>
8
</ThirdPartyComponent>
9
</div>
10
</template>
Now every component that uses WrapperComponent
can use the slots of ThirdPartyComponent
.
What's happening:
- We insert the third-party component and bind its attributes via the
$attrs
component instance object (official docs) - We loop over all available slots using the
$slots
component instance object (official docs) and bind the slots props to the slot name via#[name]="slotProps"
- In the
slot
, we usev-bind
to bind all third-party slot properties (slotProps
) to pass out to a parent
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Vue Tip: Lifecycle Hooks for DebuggingSep 26, 2022
Vue Tip: Expose Properties in a Script Setup ComponentOct 8, 2022
Show comments