In Vue.js, slots are placeholders within a component's template that allow the parent component to inject content into the child component. Slots provide a flexible way to compose components and enable the creation of reusable and customizable components.
Types of slots in Vue.js
There are two types of slots in Vue.js.
- Named Slots: Named slots allow the parent component to inject content into specific named placeholders within the child component's template.
- Scoped Slots: Scoped slots allow the child component to pass data back to the parent component, enabling more dynamic content generation and composition.
Here's a brief explanation of each type of slot.
1. Named Slots
Named slots are defined in the child component's template using the <slot>
element with a name
attribute. The parent component then provides content for these named slots using the corresponding slot attribute.
ChildComponent.vue
<template>
<div>
<h1><slot name="header">Default Header</slot></h1>
<div><slot name="content">Default Content</slot></div>
</div>
</template>
ParentComponent.vue
<template>
<child-component>
<template v-slot:header>
<!-- Content for the header slot -->
<span>Custom Header</span>
</template>
<template v-slot:content>
<!-- Content for the content slot -->
<p>Custom Content</p>
</template>
</child-component>
</template>
2. Scoped Slots
Scoped slots allow the child component to pass data to the parent component within the slot content. This data can be accessed and manipulated by the parent component.
ChildComponent.vue
<template>
<div>
<slot :data="internalData"></slot>
</div>
</template>
<script>
export default {
data() {
return {
internalData: 'Data from child component'
};
}
}
</script>
ParentComponent.vue
<template>
<child-component>
<!-- Accessing data from scoped slot -->
<template v-slot="{ data }">
<p>{{ data }}</p>
</template>
</child-component>
</template>
In this example, the parent component accesses the data passed by the child component and renders it within its template.
Slots are powerful features in Vue.js that facilitate component composition, reusability, and customization. They provide a flexible way to build complex UIs while maintaining a clear separation of concerns between parent and child components.