Vue Slots
Vue’s slots are a strong feature that enable more adaptable and reusable components.
To transport material from the parent component into the <template> of a child component, we use slots in Vue.
Slots
Thus far, we have only employed elements within <template> as self-closing tags, as demonstrated by this:
App.vue:
q
Alternatively, we can enclose some material, such as a text, within opening and closing tags:
App.vue:
Hello World!
However, we must utilize the <slot> element inside the component in order to receive “Hello World!” inside the component and display it on our website. The <slot> tag serves as a placeholder for the content, which will be replaced by the material sent to the application after it has been constructed.
Example
SlotComp.vue:
SlotComp.vue
Slots as Cards
To create a card-like appearance, longer sections of dynamic HTML content can also be wrapped around slots.
Instead of sending data as props to construct content inside components as we did previously, we may now transmit the HTML content straight inside the <slot> tag.
Example
App.vue:
Slots in Vue
We create card-like div boxes from the foods array.
{{x.name}}
{{x.desc}}
To generate a card-like appearance around the content without affecting other divs in our application, we utilize a div around the <slot> and style the <div> locally as the material enters the component where the <slot> sits.
SlotComp.vue:
It is possible to construct new pieces with the same card-like frame around them by reusing components that produce a card-like frame around content.
In this example, we create a footer using the same component as the meal items.
Example
App.vue:
Reusable Slot Cards
We create card-like div boxes from the foods array.
We also create a card-like footer by reusing the same component.
{{x.name}}
Fallback Content
Fallback content can be created in the <slot> if a component is built without any content.
Example
This application’s fallback content is rendered because the initial component lacks any content.
App.vue:
Slots Fallback Content
A component without content provided can have fallback content in the slot tag.
This content is provided from App.vue
SlotComp.vue:
This is fallback content