JAVASCRIPT

Flexible Content Distribution with Vue 3 Slots

Enhance component reusability in Vue 3 by using slots to inject and distribute dynamic content from parent components.

<!-- CardComponent.vue -->
<template>
  <div style="border: 1px solid #ccc; padding: 15px; margin: 10px; border-radius: 5px;">
    <header v-if="$slots.header" style="border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 10px;">
      <slot name="header">Default Header Content</slot>
    </header>
    <main>
      <slot>Default Main Content</slot>
    </main>
    <footer v-if="$slots.footer" style="border-top: 1px solid #eee; padding-top: 10px; margin-top: 10px;">
      <slot name="footer">Default Footer Content</slot>
    </footer>
  </div>
</template>

<!-- ParentApp.vue -->
<script setup>
import CardComponent from './CardComponent.vue';
</script>

<template>
  <h1>Using Card Components with Slots</h1>

  <CardComponent>
    <!-- Default slot content -->
    <p>This is the main content for Card 1.</p>
    <button>Click Me</button>
  </CardComponent>

  <CardComponent>
    <!-- Named slot for header -->
    <template #header>
      <h2>Custom Card Title</h2>
    </template>
    <!-- Default slot content -->
    <p>Here's some custom body text for Card 2.</p>
    <!-- Named slot for footer -->
    <template #footer>
      <small>Card 2 Footer Info</small>
    </template>
  </CardComponent>

  <CardComponent>
    <!-- Only header slot content -->
    <template #header>
      <h3>Important Alert!</h3>
    </template>
    <!-- No default slot content provided, will use default from CardComponent -->
    <!-- No footer slot content provided -->
  </CardComponent>
</template>
How it works: This snippet demonstrates how Vue 3 slots enable flexible content distribution within components. The `CardComponent` defines a default slot and named slots (e.g., `header`, `footer`) using the `<slot>` element. Parent components then pass content into these slots, either directly for the default slot or using `<template #slotName>` for named slots. This allows the `CardComponent` to render diverse content while maintaining its own structure and styling, making it highly reusable. The `$slots` object is used to conditionally render sections only if content is provided for a named slot.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs