--- title: Slot Content Only Has Access to Parent Component Scope impact: HIGH impactDescription: Attempting to access child component data in slot content results in undefined values or errors type: gotcha tags: [vue3, slots, scope, reactivity, common-mistake] --- # Slot Content Only Has Access to Parent Component Scope **Impact: HIGH** - Slot content is compiled in the parent component's scope and cannot access data defined in the child component. This follows JavaScript's lexical scoping rules and is a common source of confusion. When you provide content for a slot, that content is defined in your parent template and can only access data available in the parent component. The child component's internal state is not accessible unless explicitly passed via scoped slots. ## Task Checklist - [ ] Remember that slot content is compiled in parent scope - [ ] Never try to access child component data directly in slot content - [ ] Use scoped slots when child data needs to be exposed to parent - [ ] Check that all template expressions reference data available in the current component **Incorrect:** ```vue ``` ```vue ``` **Correct - Use Scoped Slots:** ```vue ``` ```vue ``` **Correct - Use Parent Data:** ```vue ``` ## The Function Analogy Think of slots as function parameters: ```javascript // Slot content is like a callback defined in parent scope function Parent() { const parentData = 'Hello' // This callback can only see parentData, not childData Child((slotProps) => { return parentData + (slotProps?.text || '') }) } function Child(slotCallback) { const childData = 'World' // Not visible to callback // Must explicitly pass data via slot props return slotCallback({ text: childData }) } ``` ## Reference - [Vue.js Slots - Render Scope](https://vuejs.org/guide/components/slots.html#render-scope)