Questions
What are slots and how do you use them in Vue?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that will be used to display a user’s profile information.
The component needs to be flexible enough to be used in a variety of different contexts. For example, you want to be able to use it to display a user’s profile in a sidebar, in a modal, and on a user’s profile page.
The Challenge
Explain what slots are in Vue and how you would use them to solve this problem. What are the key benefits of using slots?
A junior engineer might try to solve this problem by creating a separate component for each use case. This would be a very verbose and difficult to maintain solution.
A senior engineer would know that slots are the perfect tool for this job. They would be able to explain what slots are and how to use them to create a flexible and reusable component.
Step 1: Understand What Slots Are
Slots are a mechanism for content distribution in Vue components. They allow you to pass content from a parent component to a child component.
Step 2: The Different Types of Slots
| Type | Description |
|---|---|
| Default Slot | The default slot is a single slot that can be used to pass any content to a child component. |
| Named Slots | Named slots allow you to pass multiple pieces of content to a child component, each with its own name. |
| Scoped Slots | Scoped slots allow you to pass data from the child component back up to the parent component. |
Step 3: Use Slots to Create a Flexible Component
Here’s how we can use slots to create a flexible UserProfile component:
UserProfile.vue:
<template>
<div class="user-profile">
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>Parent Component:
<template>
<UserProfile>
<template v-slot:header>
<h1>{{ user.name }}</h1>
</template>
<p>{{ user.bio }}</p>
<template v-slot:footer>
<a :href="user.website">Website</a>
</template>
</UserProfile>
</template>
<script>
import UserProfile from './UserProfile.vue';
export default {
components: {
UserProfile
},
data() {
return {
user: {
name: 'John Doe',
bio: '...',
website: '...'
}
};
}
};
</script>In this example, we use named slots to allow the parent component to pass a header, a body, and a footer to the UserProfile component.
Practice Question
You want to create a reusable button component that can display an icon and some text. Which of the following would be the most appropriate?