JAVASCRIPT
Using Slots for Flexible Content Distribution in Vue 3 Components
Master Vue 3 slots to enable content distribution, making your components highly flexible and reusable by allowing parents to inject custom UI.
// src/components/MyCard.vue
<template>
<div class="card">
<header class="card-header">
<slot name="header">Default Header Content</slot>
</header>
<div class="card-body">
<slot>Default Body Content</slot>
</div>
<footer class="card-footer">
<slot name="footer" :year="currentYear">Default Footer ({{ currentYear }})</slot>
</footer>
</div>
</template>
<script setup>
import { ref } from 'vue';
const currentYear = ref(new Date().getFullYear());
</script>
<style scoped>
.card {
border: 1px solid #eee;
border-radius: 8px;
padding: 16px;
margin: 16px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
max-width: 300px;
}
.card-header {
font-weight: bold;
margin-bottom: 8px;
color: #333;
}
.card-body {
margin-bottom: 8px;
color: #555;
}
.card-footer {
font-size: 0.8em;
color: #777;
}
</style>
// src/App.vue
<template>
<MyCard>
<template #header>
<h2>Custom Card Title</h2>
</template>
<p>This is some custom content for the card body.</p>
<template #footer="{ year }">
<p>© {{ year }} My Company</p>
</template>
</MyCard>
<MyCard /> <!-- Card with default slot content -->
</template>
<script setup>
import MyCard from './components/MyCard.vue';
</script>
How it works: Slots are a powerful feature in Vue 3 that allow components to receive and distribute content from their parent components. This enables the creation of highly flexible and reusable UI components. This snippet demonstrates default, named, and scoped slots. Default slots are used for general content, named slots (`<slot name="header">`) provide specific insertion points, and scoped slots (`<slot name="footer" :year="currentYear">`) allow child components to expose data to the parent when rendering content for that slot, accessed via `v-slot="{ year }"`.