Slots in Vue are a powerful feature that allows us to create flexible and reusable components.
They enable us to pass content from a parent component to a child component, allowing for dynamic composition of the component's template structure.
Named slots allow us to define "multiple slots" in a "child component" and pass content to each slot from the "parent component" using "named slots".
// ChildComponent.vue <template> <div> <slot name="header"></slot> <div> <slot></slot> </div> <slot name="footer"></slot> </div> </template>
// ParentComponent.vue: <template> <ChildComponent> <template v-slot:header> <h1>This is the header slot</h1> </template> <div> <h1>This content goes into the default slot</h1> </div> <template v-slot:footer> <footer>This is the footer slot</footer> </template> </ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent } }; </script>
"v-slot" is a directive in Vue used for defining slots in a parent component when using the syntax.
It allows us to specify where the content provided by the parent should be placed within the child component.
This directive is part of the new slot syntax introduced in Vue 2.6.0.
We use the tag with the v-slot directive to define named slots (header and footer) and the default slot.
Content within each tag defines what will be rendered in the respective slots.
Scoped slots allow the child component to pass data back to the parent component.
They are useful when the parent component needs to customize the content passed to the child component based on some data or logic.
// ChildComponent.vue <template> <div> <slot :message="message"></slot> </div> </template> <script> export default { data() { return { message: 'Hello from child!' }; } }; </script>
<template> <ChildComponent v-slot="{ message }"> <p>{{ message }}</p> </ChildComponent> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent } }; </script>
Slots are a versatile feature in Vue that allows for component composition and reusability, making it easier to build complex user interfaces.
They provide a clean and flexible way to customize and inject content into components.