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).
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 !!
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With