JAVASCRIPT

Vue 3 Component Flexibility with Slots (Default, Named, Scoped)

Master Vue 3 slots to create highly flexible and reusable components, allowing parent components to inject custom content (default, named, scoped).

// CardComponent.vue
<template>
  <div class="card">
    <header v-if="$slots.header">
      <slot name="header"></slot>
    </header>
    <main>
      <slot :user="cardUser"></slot> <!-- Default slot with scope -->
    </main>
    <footer v-if="$slots.footer">
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

<script setup>
import { reactive } from 'vue';

const cardUser = reactive({
  name: 'Jane Doe',
  age: 28
});
</script>

<style scoped>
.card {
  border: 1px solid #ccc;
  padding: 15px;
  margin: 10px;
  border-radius: 8px;
}
</style>

// App.vue (Parent Component using CardComponent)
<template>
  <div>
    <CardComponent>
      <!-- Named slot for header -->
      <template #header>
        <h2>Welcome to My Card!</h2>
      </template>

      <!-- Default / Scoped slot -->
      <template v-slot="{ user }">
        <p>This is the main content of the card.</p>
        <p>User from slot: {{ user.name }} ({{ user.age }} years old)</p>
      </template>

      <!-- Named slot for footer -->
      <template #footer>
        <button>Learn More</button>
      </template>
    </CardComponent>

    <CardComponent>
      <!-- Using only default slot -->
      <p>This is another card with just default content.</p>
    </CardComponent>
  </div>
</template>

<script setup>
import CardComponent from './CardComponent.vue';
</script>
How it works: This snippet demonstrates the power of slots in Vue 3 for building highly flexible and reusable components. It covers three types: default slots (for general content), named slots (for specific content areas like `header` or `footer`), and scoped slots (which allow the child component to pass data back to the parent component when rendering the slot content, as seen with the `user` object). Slots enable a component to define content placeholders, letting its parent dictate what content fills those placeholders, leading to more modular and configurable UI components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs