Skip to content

Instantly share code, notes, and snippets.

@rhysburnie
Last active January 25, 2023 13:43
Show Gist options
  • Save rhysburnie/a255e7246d919872029b17d4b2b26419 to your computer and use it in GitHub Desktop.
Save rhysburnie/a255e7246d919872029b17d4b2b26419 to your computer and use it in GitHub Desktop.
vue3 determine if slot is being used (has content)
import { useSlots } from 'vue';
export default function useHasSlot() {
const slots = useSlots();
return function hasSlot(name) {
return slots[name] && !isEmptySlot(slots[name]());
};
}
function isEmptySlot(items) {
if (!items.length) return true;
return !items.some(hasSlotContent);
}
function hasSlotContent(item) {
const type = item.type.toString();
if (type === 'Symbol(Comment)') return false;
if (type === 'Symbol(Text)' && !item.children.trim()) return false;
return true;
}
@rhysburnie
Copy link
Author

setup() {
  return { hasSlot: useHasSlot() }
}

v-if="hasSlot('default')" etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment