In certain scenarios, you want to pass on all slots from a parent component to the child component. This is especially useful when creating a wrapper component that adds some functionality to the child component.
In this article, let's assume we have a Child.vue
component with two named slots, top
and bottom
:
<template>
<div>
<h2>Child</h2>
<slot name="top" />
<slot name="bottom" />
</div>
</template>
Child.vue
is wrapped by the Parent.vue
component that should pass all slots to its child component. First, let's see how the named slots are filled in the App.vue
component:
<template>
<Parent>
<template #top>
<span>Top</span>
</template>
<template #bottom>
<span>Bottom</span>
</template>
</Parent>
</template>
Finally, let's see how the Parent.vue
component passes all slots to its child component:
<template>
<div>
<h1>Parent</h1>
<Child>
<template v-for="(_, slotName) in $slots" #[slotName]>
<slot :name="slotName" />
</template>
</Child>
</div>
</template>
We iterate over the $slots
object and render a slot
element for each slot. The slot
element has a :name
attribute that is bound to the slotName
variable.
StackBlitz
Try it out on StackBlitz:
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :