You can check if a slot is empty, for example, only to render it if it is available or has content.
Check if a slot is empty
To check if a slot is empty, you can use $slots
, an object representing the slots passed by the parent component.
Each slot is exposed on $slots
as a function that returns an array of vnodes
under the key corresponding to that slot's name. The default slot is exposed as $slots.default
.
If a slot is a scoped slot, arguments passed to the slot functions are available to the slot as its slot props.
In the following example, the footer is only rendered if the slot with the name footer
is present:
Vue 2 Code
Of course, you can use that functionality in Vue 2 as well:
useSlots composable
Usage of slots inside <script setup>
should be relatively rare since you can directly access them as $slots
in the template. In the rare case where you need them, you can use the useSlots
composable:
Info
useSlots
is a runtime function that returns the equivalent of setupContext.slots
. You can use it in normal Composition API functions as well.
Check if a slot has content
In some cases, you probably want to check if the slot is not empty and has content inside.
You can do that by checking the array of vnodes
, if they are empty or not:
StackBlitz
The code for this tip is interactively available in the following StackBlitz project:
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:
Vue Tip: Memoize a Sub-Tree of the Template Using v-memo
The v-memo directive is like a computed prop for the template.
Vue Tip: Delay Loading Appearance of Spinner
Eager delay spinners are not a good user experience. They can make a snappy user interface feel slower. We want delay spinners to appear only after a perceivable delay.