Slots
Slots allow you to pass content into a component.
Let's add a <slot>
tag to our component called my-first-component
. <slot>
tags are placeholders for content.
<template>
<slot />
</template>
Slots can contain default values.
<template>
<slot>Anything in here will show up if no other value is provided</slot>
</template>
If you insert this component into an email, you can replace the default content:
<x-base>
<x-section>
<my-first-component>
text that replaces the default content of the slot
</my-first-component>
</x-section>
</x-base>
For example, you might make a button that has the default content of “Learn more” when no text is passed in.
Sometimes you’ll have a component that needs more than one slot. For example, a <layout>
component might take in a header slot, main slot, and footer slot.
This can be accomplished with named slots.
Add a name
attribute to the <slot>
element. If you don’t add the name
attribute, it will be named default
(like the second slot below).
<!-- <layout> source -->
<template>
<div><slot name="header"/></div>
<div><slot /></div>
<div><slot name="footer"/></div>
</template>
You can now use the <layout>
component like so:
<layout>
<fragment #slot="header">This goes in the header slot</fragment>
<fragment>This goes in the default slot</fragment>
<fragment #slot="footer">This goes in the footer slot</fragment>
</layout>
Just like with properties, we can validate the values in slots. We have a more limited set of types we check against, focused on content.
Use the Component.slots
global variable to define the slot validation:
children
- specifies which elements and components are allowed to be inserted into the slotmax
- specifies the max number of children allowed, only chainable onchildren
min
- specifies the minimum number of children allowed, only chainable onchildren
text
- specifies a slot may contain text and inline marks
export const slots = Component.defineSlots({
slot1: Component.slots.children(['child-component-1', 'child-component-2']).min(1).max(10),
slot2: Component.slots.text(),
})
We do not validate the fallback content against the slot definitions.
You can also specify when components can only have certain parent components.