Skip to main content

What is useSlots()?

useSlots() is a function from the Composition API in Vue 3 that lets you access all of a component's slots inside setup().

In simple terms:

useSlots() is a way to work with slots in the Composition API in the same way this.$slots does in the Options API.


How to use useSlots()

js
import { useSlots } from 'vue' export default { setup() { const slots = useSlots() console.log(slots) // an object with all slots return {} } }

What useSlots() returns

useSlots() returns an object shaped like:

js
{ default: Function | undefined, header: Function | undefined, footer: Function | undefined }

Each property is a function that renders the slot's content.


Example: checking whether the parent passed a slot

Child component:

vue
<script setup> import { useSlots } from 'vue' const slots = useSlots() const hasHeader = !!slots.header </script> <template> <div class="card"> <div v-if="hasHeader" class="header"> <slot name="header" /> </div> <div class="body"> <slot /> </div> </div> </template>

This way you can show the header only if the parent passed content for the slot.


Example: counting elements in the default slot

js
const slots = useSlots() onMounted(() => { const vnodes = slots.default?.() console.log('Default slot contains', vnodes.length, 'elements') })

When is useSlots() needed?

1. When you need to check whether a slot exists

For example, showing the header only if it was passed.

2. When you need to process the slot's content programmatically

For example, counting elements, modifying them, selecting the ones you need.

3. When you are working with the Composition API

Unlike the Options API, there is no this.$slots, so useSlots() is used instead.

4. When building wrappers, layouts, or UI libraries

Slots are the main mechanism for such components.


Summary (great for an interview)

useSlots() is a Composition API function that returns an object with the component's slots. It lets you check whether slots exist, render them programmatically, and work with slots inside setup(), similarly to this.$slots in the Options API.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.