现在,随着 Svelte 5 的预发布,我觉得我可以表达对 Svelte 5 中插槽的一些困惑。在 Svelte 4 中,插槽和命名插槽通过以下方式完成:
ContactCard.svelte
<article class="contact-card">
<h2>
<slot name="name">
<span class="missing">Unknown name</span>
</slot>
</h2>
<div class="address">
<slot name="address">
<span class="missing">Unknown address</span>
</slot>
</div>
<div class="email">
<slot name="email">
<span class="missing">Unknown email</span>
</slot>
</div>
</article>
<style>...</style>
+page.svelte
<script>
import ContactCard from './ContactCard.svelte';
</script>
<ContactCard>
<span slot="name"> P. Sherman </span>
<span slot="address">
42 Wallaby Way<br />
Sydney
</span>
</ContactCard>
以我的愚见,非常简单和直接。
Component.svelte
<script>
let { children } = $props();
</script>
<div>
{@render children()}
</div>
+page.svelte
<script>
import { Component } from '$lib';
</script>
<Component>
...content...
</Component>
也很容易...
在这个新范式中我们如何做“命名槽”
您只需在组件内定义一个
#snippet
即可。<script>
import ContactCard from './ContactCard.svelte';
</script>
<ContactCard>
{#snippet name()} P. Sherman {/snippet}
{#snippet address()}
42 Wallaby Way<br />
Sydney
{/snippet}
</ContactCard>
(如果您需要
span
元素,您可以将它们添加到代码片段中。)
<!-- ContactCard.svelte -->
<script>
let { name, address } = $props();
</script>
<div>
<div class="name">{@render name()}</div>
<div class="address">{@render address()}</div>
</div>
片段可以在组件外部定义,也可以显式传递:
{#snippet name()} P. Sherman {/snippet}
{#snippet address()}
42 Wallaby Way<br />
Sydney
{/snippet}
<ContactCard {name} {address} />