Javascript is required
ยท
1 min read

Vue Tip: Passing Slots to Child Components

Vue Tip: Passing Slots to Child Components Image

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:

Child.vue
1<template>
2  <div>
3    <h2>Child</h2>
4    <slot name="top" />
5    <slot name="bottom" />
6  </div>
7</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:

App.vue
1<template>
2  <Parent>
3    <template #top>
4      <span>Top</span>
5    </template>
6    <template #bottom>
7      <span>Bottom</span>
8    </template>
9  </Parent>
10</template>

Finally, let's see how the Parent.vue component passes all slots to its child component:

Parent.vue
1<template>
2  <div>
3    <h1>Parent</h1>
4    <Child>
5      <template v-for="(_, slotName) in $slots" #[slotName]>
6        <slot :name="slotName" />
7      </template>
8    </Child>
9  </div>
10</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 X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.