Javascript is required
Mokkapps Logo

Vue Tip: Check if Slot Is Empty

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Jul 6, 2022
1 min read
Check if Slot Is Empty Image

We can check if a slot is empty, for example, only to render it if it has content. For this, we can use $slots, an object representing the slots passed by the parent component.

Each slot is exposed on this.$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 this.$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 name footer is present:

<template>  <footer v-if="$slots.footer">    <h3>My Footer Heading</h3>    <slot name="footer" />  </footer></template>

Usage of slots inside <script setup> should be relatively rare, since we can directly access them as $slots in the template. In the rare case where we need them, we can use the useSlots helper:

<template>  <footer v-if="showFooter">    <h3>My Footer Heading</h3>    <slot name="footer" />  </footer></template><script setup>import { useSlots } from 'vue'const slots = useSlots()const showFooter = () => {  return !!slots.footer}</script>

useSlots is a runtime functions that returns the equivalent of setupContext.slots. We can use it in normal composition API functions as well.

Finally, let's take a look at the corresponding Vue 2 code:

<template>  <footer v-if="showFooter">    <h3>My Footer Heading</h3>    <slot name="footer" />  </footer></template><script>export default {  data() {    return {      showFooter: false,    }  },  created() {    this.setShowSlots()  },  beforeUpdate() {    this.setShowSlots()  },  methods: {    setShowSlots() {      this.showFooter = this.$slots.footer?.[0]    },  },}</script>

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more content from me. Alternatively (or additionally), you can also subscribe to my newsletter.