We can dynamically generate slots at runtime, giving us even more flexibility in how we write our components:
<!-- Child.vue --><template><div v-for="step in steps" :key="step.id"><slot :name="step.name" /></div></template>
Each of these slots works like any other named slot. This is how we would provide content to them:
<!-- Parent.vue --><template><Child :steps="steps"><!-- Use a v-for on the template to provide contentto every single slot --><template v-for="step in steps" v-slot:[step.name]><!-- Slot content in here --></template></Child></template>
We pass all of our steps
to the Child
component so it can generate the slots. Then we use a dynamic directive argument v-slot:[step.name]
inside a v-for
to provide all of the slot content.
When might you need something like this?
I can imagine one use case for a complex form generated dynamically. Or a wizard with multiple steps, where each step is a unique component.
I'm sure there are more!