具名插槽的使用场景
- 复杂布局组件:当组件需要在不同位置呈现不同内容时,比如一个卡片组件,卡片头部、卡片主体和卡片底部需要插入不同内容。
- 可复用模板:在创建可复用的模板组件时,通过具名插槽让使用者可以灵活地填充特定位置的内容,像模态框组件,标题、内容区域和按钮区域可以分别用具名插槽。
- 特定功能区域:组件内有特定功能的区域,如表单组件中的错误提示区域,使用具名插槽方便父组件插入合适的错误提示内容。
具名插槽的Svelte组件示例代码
{#if showModal}
<div class="modal">
<div class="modal-content">
<slot name="header">默认标题</slot>
<slot>默认内容</slot>
<slot name="footer">
<button on:click={() => showModal = false}>关闭</button>
</slot>
</div>
</div>
{/if}
父组件中向具名插槽插入内容
<script>
import Modal from './Modal.svelte';
let showModal = true;
</script>
<Modal {showModal}>
<span slot="header">自定义标题</span>
<p>这是自定义的内容</p>
<button slot="footer" on:click={() => showModal = false}>自定义关闭按钮</button>
</Modal>