Slots in Vue 3: A Comprehensive Guide
In Vue 3, slots are a way to pass content from a parent component to a child component. Slots allow you to customize and reuse components by allowing you to specify the content that a component should render. In this tutorial, we'll take a look at how to use slots in Vue 3 to build dynamic and reusable user interfaces.
To define a slot in Vue 3, you can use the <slot>
element in the component's template. The <slot>
element represents a placeholder for the content that will be passed from the parent component. You can specify a default content for the slot using the v-if
directive and the v-else
element.
For example, let's say you have a component called Card
that renders a card element, and you want to allow the parent component to specify the content of the card:
<template>
<div class="card">
<slot v-if="!hasContent" name="default">
No content
</slot>
<slot v-else>
<slot name="header"></slot>
<slot name="body"></slot>
<slot name="footer"></slot>
</slot>
</div>
</template>
<script>
export default {
computed: {
hasContent() {
return this.$slots.default && this.$slots.default.length > 0;
},
},
};
</script>
In this example, the Card
component is defined in the export default
object, and the template
contains a <div>
element with the card
class that represents the card element. The template
also contains two <slot>
elements: one for the default slot and one for the named slots. The default slot has a v-if
directive that checks if the default slot has any content, and the named slots are used to render the header, body, and footer of the card.
To use the Card
component in your application, you can use the <Card>
element in a template and specify the content of the slots using the <template>
element:
<template>
<Card>
<template #default>
<h1>Card title</h1>
<p>Card content</p>
</template>
<template #header>
<h2>Card header</h2>
</template>
<template #footer>
<p>Card footer</p>
</template>
</Card>
</template>
<script>
import Card from './Card.vue';
export default {
components: {
Card,
},
};
</script>
In this example, the Card
component is imported and registered in the components
option, and the Card
element is used in the template to render the Card
component. The <template>
elements are used to specify the content of the slots, and the #
syntax is used to specify the name of the slot. The default
slot is used to specify the content of the card, and the header
and footer
slots are used to specify the header and footer of the card.
By using slots, you can customize and reuse components in different parts of your application. Whether you're building a simple form or a complex single-page application, slots are a key feature for building dynamic and reusable UIs with Vue 3.