Vue Tip: Use Scoped Slots in a Child Component to Provide Data for Parent Component
Slots are mighty, but they are not almighty. For example, slot content does not have access to the state in the child component.
There are cases where you want to provide data for presentation in the parent component. For that, you can use Scoped Slots.
Using scoped slots, a child component can pass data to a slot when rendering it:
Let's first take a look at receiving props using a single default slot first. For this, we can use the v-slot directive on the child component tag:
The following graphic illustrates the process of passing props from the child to the parent component:
You can think of a scoped slot as a function passed into the child component. The child component then calls it, passing props as arguments:
Info
The above code almost represents how Vue compiler compiles scoped slots and how you would use them in manual render functions.
As v-slot="slotProps"
matches the slot function signature, you can destructure the object in v-slot
:
Of course, you can also use scoped slots with named slots:
Info
The code for this demo is interactively available at StackBlitz:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Use DevTools to Know Your App Better
Nuxt DevTools is a set of visual tools that help you to know your app better.
Vue Tip: Debugging in Templates
Guide to debug Vue component templates using the Browser DevTools.