Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Slots and Component Composition | Transitions and Component Composition
Introduction to Svelte

Slots and Component Composition

メニューを表示するにはスワイプしてください

Reusable components often need flexible content that changes depending on where the component is used. Instead of hardcoding all content directly inside a component, Svelte allows developers to insert custom content using slots.

Slots make components more flexible and easier to reuse in larger applications.

What Are Slots?

A slot is a placeholder inside a component where parent components can insert custom content.

This allows the same component structure to display different content in different situations.

Creating a Component with a Slot

Create a file called Card.svelte.

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

<style>
  .card {
    padding: 20px;
    border-radius: 12px;
    background-color: #f3f4f6;
  }
</style>

The <slot> element acts as a content placeholder.

Passing Content into the Slot

Open App.svelte and use the component:

<script>
  import Card from './Card.svelte';
</script>

<Card>
  <h2>Welcome</h2>
  <p>This content comes from the parent component.</p>
</Card>

The content placed between the opening and closing component tags appears inside the slot.

Why Slots Are Useful

Slots make components much more flexible.

For example, the same card component could display:

  • User profiles;
  • Product information;
  • Notifications;
  • Settings panels;
  • Dashboard widgets.

The structure stays reusable while the content changes dynamically.

Component Composition

Using components together to build larger interfaces is called component composition.

Instead of creating one massive component, developers combine smaller reusable components into larger application structures.

This approach helps frontend applications remain organized and scalable.

question mark

What is the purpose of a <slot> element in a Svelte component?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 6.  4
some-alt