Wednesday, June 22, 2022

Checking if user passed a slot in Vue

In Vue 3 with the Composition API, there is no this.$slot entry to programmatically poke on the slots. You must summon the slots by calling useSlots() – yes, that’s a React hook right there.

The returned object has one entry for each slot. If your component has only one unnamed slot, it will be named 'default'. So, in order to check whether the user didn’t pass the slot, you simply check whether the entry exists:

<script setup lang="ts">
import {computed, useSlots} from 'vue';

const slots = useSlots();
const hasSlot = computed(() => slots['default'] !== undefined);
</script>

No comments: