Introduction to Vue.js Slots

Vue.js slots provide a powerful mechanism for flexible component composition. They allow you to create dynamic and reusable components by providing a way to pass content and elements to a component from its parent. In this guide, we'll explore how to use Vue.js slots effectively to build versatile and customizable components.


Basic Slot Usage

Slots are defined in the component's template using the `` element. The parent component can then insert content into the slot. Here's a simple example of a component with a slot:


<div id="app">
<my-component>
<p>This is the content of the slot.</p>
</my-component>
</div>
<script>
Vue.component('my-component', {
template: `
<div>
<h2>My Component</h2>
<slot></slot>
</div>
`
});
new Vue({
el: '#app'
});
</script>

In this example, the `` accepts and displays the content passed to it between the tags. The `` element serves as a placeholder for this content.


Named Slots

Vue.js allows you to define named slots, providing even more flexibility. You can have multiple named slots in a component and specify where the content should go. Here's an example:


<div id="app">
<my-component>
<template v-slot:header>
<h2>This is the header slot</h2>
</template>
<template v-slot:content>
<p>This is the content of the content slot.</p>
</template>
</my-component>
</div>
<script>
Vue.component('my-component', {
template: `
<div>
<slot name="header"></slot>
<slot name="content"></slot>
</div>
`
});
new Vue({
el: '#app'
});
</script>

In this example, we define named slots ("header" and "content") and specify where to place the content within the `` template.


Scoped Slots

Scoped slots allow the parent component to pass data to the child component. The child component can then use this data within the slot content. Here's an example:


<div id="app">
<my-component>
<template v-slot:default="slotProps">
<p>{{ slotProps.message }}</p>
</template>
</my-component>
</div>
<script>
Vue.component('my-component', {
data() {
return {
message: 'Hello from the parent component!'
};
},
template: `
<div>
<slot :message="message"></slot>
</div>
`
});
new Vue({
el: '#app'
});
</script>

In this example, the parent component passes a message to the child component's slot, and the child component displays it using the `slotProps`.


Conclusion

Vue.js slots offer a versatile way to create dynamic and reusable components. Whether you need simple content insertion or more complex component composition with named or scoped slots, Vue.js slots provide the flexibility to customize and extend your components as needed.