Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue3 Check if a Slot is Empty

Tags:

vue.js

vuejs3

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).

like image 393
DreadedSlug Avatar asked Jun 30 '21 00:06

DreadedSlug


People also ask

How do I know if my Vue slot has content?

To only show slot if it has content with Vue. js, we can check the this. $slots property in our component. to check if the footer slot is added with !!

What is Slot scope in Vue?

Scoped slots allow you to pass a template to the slot instead of passing a rendered element. It's called a "scoped" slot because although the template is rendered in the parent scope, it will have access to certain child data. For example, a component child with a scoped slot might look like the following.


Video Answer


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

like image 196
tony19 Avatar answered Oct 27 '22 09:10

tony19


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

<script setup>
const slots = useSlots()
const hasSlot = (name) => {
    return !!slots[name];
  }
</script>
like image 22
Sunghyun Cho Avatar answered Oct 27 '22 08:10

Sunghyun Cho