Checking if a slot is empty in Vue

jacobandrewsky

Jakub Andrzejewski

Posted on September 23, 2024

Checking if a slot is empty in Vue

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>


Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

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 🖥️

💖 💪 🙅 🚩
jacobandrewsky
Jakub Andrzejewski

Posted on September 23, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Checking if a slot is empty in Vue
vue Checking if a slot is empty in Vue

September 23, 2024