Hey there!
In one of my Vue projects, I recently needed to check if a slot is empty. The use case for that was a compontent that could accept a slot for some content but it could also work without it. For that, I looked at Vue docs and did some experimenting myself to see if I can make it work and I was pleasantly surprised that this is yet another very useful feature that comes built in to the Vue framework.
There can be actually several reasons why you you may want to check if a slot is empty but probably the main one would be to do it only if a slot was actually passed to the component.
Today, I wanted to share this useful tip with you so that you could start using it in your projects.
Enjoy!
π’ Checking if slot is empty in Vue
In order to do it, you could use a built in Vue object $slots
which is always passed by the parent component. Each slot is exposed as a function that returns an array of vnodes
under the key corresponding to that slot's name - with just one unique case for default slot which will be accessed as $slots.default
.
In the following example, the <header>
is only rendered if the slot with the name header
is present:
<template>
<header v-if="$slots.header">
<h1>My Awesome Heading</h1>
<slot name="header" />
</header>
</template>
Usually you would use slots directly in the template but you can work with slots in the script
- you would need to use a built in useSlots
composable that will return setupContext.slots
.
To achieve similar result as in above example, we would need following code:
<script setup lang="ts">
import { useSlots } from 'vue'
const slots = useSlots()
const shouldShowHeader = () => !!slots.header
</script>
<template>
<header v-if="shouldShowHeader">
<h1>My Awesome Heading</h1>
<slot name="header" />
</header>
</template>
As we can see from the examples above, it is really easy to check if a slot is empty in Vue by using the template or script approach :)
π Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects π
β Summary
Well done! You have just learned how to check if a slot is empty in Vue.
Take care and see you next time!
And happy coding as always π₯οΈ
Top comments (3)
Thanks a lot π
I was always wondering how PrimeVue hides the header and footer slots conditionally
Hey mate, recommend some course for VueJs+typescript+testing. Where they teach design patterns, performance, best practices around VueJs.
Your help would be appreciated.
I would highly recommend video tutorial by my friend Alex -> youtube.com/watch?v=yGzwk9xi9gU