当前位置: 首页>数据库>正文

Getting started with Svelte - Component composition

Getting started with Svelte - Component composition,第1张

Just like elements can have children so can components. Before a component can accept children, though, it needs to know where to put them. We do this with the <slot> element.

Box.svelte

<div class="box">
    <slot></slot>
</div>

App.svelte

<Box>
    <h2>Hello!</h2>
    <p>This is a box. It can contain anything.</p>
</Box>

Named slots

Named slots allow consumers to target specific areas. They can also have fallback content.

A component can specify fallbacks for any slots that are left empty, by putting content inside the <slot> element.

Widget.svelte

<div>
    <slot name="header">No header was provided</slot>
    <p>Some content between header and footer</p>
    <slot name="footer" />
</div>

App.svelte

<Widget>
    <h1 slot="header">Hello</h1>
    <p slot="footer">Copyright (c) 2019 Svelte Industries</p>
</Widget>

Slot props

Slots can be rendered zero or more times and can pass values back to the parent using props. The parent exposes the values to the slot template using the let: directive.

The usual shorthand rules apply — let:item is equivalent to let:item={item}, and <slot {item}> is equivalent to <slot item={item}>.

FancyList.svelte

<ul>
    {#each items as item}
        <li class="fancy">
            <slot name="item" {item} />
        </li>
    {/each}
</ul>

<slot name="footer" />

App.svelte

<FancyList {items}>
    <div slot="item" let:item>{item.text}</div>
    <p slot="footer">Copyright (c) 2019 Svelte Industries</p>
</FancyList>

Checking for slot content by $$slots

$$slots is an object whose keys are the names of the slots passed into the component by the parent. If the parent does not pass in a slot with a particular name, that name will not be present in $$slots. This allows components to render a slot (and other elements, like wrappers for styling) only if the parent provides it.

<!-- Card.svelte -->
<div>
    <slot name="title" />
    {#if $$slots.description}
        <!-- This <hr> and slot will render only if a slot named "description" is provided. -->
        <hr />
        <slot name="description" />
    {/if}
</div>

<!-- App.svelte -->
<Card>
    <h1 slot="title">Blog Post Title</h1>
    <!-- No slot named "description" was provided so the optional slot will not be rendered. -->
</Card>

https://www.xamrdz.com/database/6v41997596.html

相关文章: