$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:
Vue School Link
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 🖥️