0
0
Vueframework~30 mins

Slots for content distribution in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Slots for Content Distribution in Vue
📖 Scenario: You are building a reusable Card component for a blog website. The card should have a title area and a content area. You want to allow users of the card to insert their own title and content inside the card using Vue slots.
🎯 Goal: Create a Vue component called Card that uses slots to let users insert custom title and content. Then use this component in a parent component, passing different titles and content inside the slots.
📋 What You'll Learn
Create a Card component with two slots: one named title and one default slot for content.
Use the Card component in a parent component and pass custom HTML inside the title slot and default slot.
Ensure the slots render the passed content inside the card layout.
💡 Why This Matters
🌍 Real World
Slots let you build flexible, reusable UI components that can accept different content from their users. This is common in design systems and component libraries.
💼 Career
Understanding slots is essential for Vue developers to create modular and maintainable components that adapt to various use cases.
Progress0 / 4 steps
1
Create the Card component with slots
Create a Vue component called Card with a template that has a <div> with class card. Inside it, add a <header> with a named slot called title and a <section> with a default slot for content. Use <slot name="title">Default Title</slot> and <slot>Default content</slot> exactly.
Vue
Need a hint?

Use <slot name="title">Default Title</slot> inside the header and <slot>Default content</slot> inside the section.

2
Import and register the Card component
In a parent Vue component, import the Card component from './Card.vue' and register it locally using components. Use the <script setup> syntax and add import Card from './Card.vue' at the top.
Vue
Need a hint?

Use import Card from './Card.vue' at the top of the script setup block.

3
Use the Card component with slots in the parent template
In the parent component template, add the <Card> component. Inside it, add a <template v-slot:title> with an <h2> containing the text My Blog Post. Also add a paragraph <p> inside the default slot with the text This is the blog post content. Use exactly <template v-slot:title> syntax.
Vue
Need a hint?

Use <template v-slot:title> to pass the title slot content and place the paragraph directly inside <Card> for the default slot.

4
Add basic styles to the Card component
In the Card.vue component, add a <style scoped> block. Inside it, add CSS to give the .card class a border of 1px solid #ccc, padding of 1rem, and border-radius of 0.5rem. This will visually separate the card content.
Vue
Need a hint?

Use a scoped style block and add CSS rules for the .card class as described.