--- title: Use $slots to Conditionally Render Slot Wrapper Elements impact: MEDIUM impactDescription: Empty wrapper elements render in DOM when slots have no content, affecting layout and styling type: best-practice tags: [vue3, slots, conditional-rendering, performance, dom-optimization] --- # Use $slots to Conditionally Render Slot Wrapper Elements **Impact: MEDIUM** - When building reusable components with optional slots, wrapper elements (divs, sections, etc.) will render even if no slot content is provided. This can cause layout issues, unnecessary DOM nodes, and styling problems. Use the `$slots` property to conditionally render wrappers only when slots have content. ## Task Checklist - [ ] Check `$slots` before rendering wrapper elements for optional slots - [ ] Use `v-if="$slots.slotName"` to conditionally render wrappers - [ ] Remember that `$slots.default` checks the default slot - [ ] Keep DOM clean by avoiding empty wrapper elements **Incorrect:** ```vue ``` When used without all slots: ```vue

Just body content

``` **Correct:** ```vue ``` Now clean DOM: ```vue

Just body content

``` ## Advanced: Using $slots in Script Setup ```vue ``` ## When to Use This Pattern | Scenario | Use $slots Check? | |----------|-------------------| | Wrapper has styling (padding, borders, background) | Yes | | Wrapper affects layout (flex, grid) | Yes | | Slot is always expected to have content | No | | No wrapper element around slot | No | | Wrapper is purely semantic (no visual impact) | Optional | ## Reference - [Vue.js Slots - Conditional Slots](https://vuejs.org/guide/components/slots.html#conditional-slots)