Last active
June 27, 2022 08:18
-
-
Save Akryum/68a4743c281a8ad3cf31dcdcb004dea6 to your computer and use it in GitHub Desktop.
Vue 3: Detect content inside slots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Doesn't work with Vue 2 scoped slots nor Vue 3 slots in some cases --> | |
<template> | |
<div> | |
<div v-if="$slots.foo"> | |
<slot name="foo" title="Title" /> | |
</div> | |
</div> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import { getSlotContent } from './slot.js' | |
export default { | |
computed: { | |
fooSlot () { | |
return getSlotContent(this.$slots.foo?.({ title: 'Title' })) | |
}, | |
FooSlot () { | |
return () => this.fooSlot | |
}, | |
}, | |
} | |
</script> | |
<template> | |
<div> | |
<div v-if="fooSlot"> | |
<component :is="FooSlot" /> | |
</div> | |
</div> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { computed, useSlots } from 'vue' | |
import { getSlotContent } from './slot.js' | |
const slots = useSlots() | |
const fooSlot = computed(() => getSlotContent(slots.foo?.({ title: 'Title' }))) | |
const FootSlot = () => fooSlot.value | |
</script> | |
<template> | |
<div> | |
<div v-if="fooSlot"> | |
<FooSlot /> | |
</div> | |
</div> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { isVNode, Comment, Fragment } from 'vue' | |
// from https://github.com/vuejs/core/blob/main/packages/runtime-core/src/helpers/renderSlot.ts#L84-L97 | |
export function getSlotContent(vnodes) { | |
if (!vnodes) return null | |
return vnodes.some(child => { | |
if (!isVNode(child)) return true | |
if (child.type === Comment) return false | |
if ( | |
child.type === Fragment && | |
!getSlotContent(child.children) | |
) return false | |
return true | |
}) | |
? vnodes | |
: null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment