Vue3 Check if a Slot is Empty

Viewed 5955

Is there a Vue3 equivalent to the following Vue2 method:

methods: {
   hasSlot(name) {
      return !!this.$slots[name]
   }
}

in Vue3's Composition API?

I've tried:

setup({slots}) {
   const hasSlot = (name) => {
      return !!slots[name];
   }

   return { hasSlot }

}

but it isn't returning the expected value as slots is undefined (per error out in console).

2 Answers

As pointed out in comments, setup()'s second argument (the context) contains the component's slots. The first argument is for the component's props.

export default {
  setup(props, { slots }) {
    const hasSlot = name => !!slots[name]
    return { hasSlot }
  }
}

demo 1

The slots are also exposed in the template as $slots, so you could replace hasSlot(slotName) with $slots[slotName] or just $slots.SLOTNAME (e.g., $slots.footer):

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

demo 2

Now, in Vue3 composition API , you can use useSlots.

<script setup>
const slots = useSlots()
const hasSlot = (name) => {
    return !!slots[name];
  }
</script>
Related