MST

星途 面试题库

面试题:Svelte中Slot的基础应用

请解释Svelte中Slot的作用,并举例说明如何在父组件中使用Slot向子组件传递内容。同时,描述当子组件中有具名Slot时,父组件应如何正确填充。
28.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

Svelte中Slot的作用

在Svelte中,Slot 用于在组件中创建一个占位符,允许父组件向子组件插入自定义内容。它使得组件具有更高的复用性和灵活性,因为子组件不需要预先知道父组件可能传递进来的具体内容。

在父组件中使用Slot向子组件传递内容的示例

假设我们有一个简单的 Card 子组件,该组件有一个 Slot 用于显示卡片的内容:

  1. 子组件 Card.svelte
<div class="card">
    <h2>Card Title</h2>
    <slot></slot>
</div>
  1. 父组件 App.svelte
<script>
    import Card from './Card.svelte';
</script>

<Card>
    <p>This is the content inside the card.</p>
</Card>

在上述例子中,父组件 App.svelte<p>This is the content inside the card.</p> 传递到 Card 组件的 Slot 位置,最终渲染出来的卡片将包含标题和这段内容。

当子组件中有具名Slot时,父组件的填充方式

具名 Slot 允许在子组件中有多个不同用途的占位符。假设 Card 组件现在有一个具名 Slot 用于显示卡片底部的内容:

  1. 子组件 Card.svelte
<div class="card">
    <h2>Card Title</h2>
    <slot></slot>
    <slot name="footer"></slot>
</div>
  1. 父组件 App.svelte
<script>
    import Card from './Card.svelte';
</script>

<Card>
    <p>This is the main content of the card.</p>
    <div slot="footer">
        <p>This is the footer content of the card.</p>
    </div>
</Card>

在这个例子中,父组件通过 slot="footer" 属性将 <div><p>This is the footer content of the card.</p></div> 传递到 Card 组件中名为 footer 的具名 Slot 位置。这样,子组件可以根据不同的具名 Slot 来渲染不同部分的内容。