Vue Tip: Dynamic Slot Names

Michael Hoffmann
Oct 7, 2023
| 1 min read
| 34 views
Michael Hoffmann
Oct 7, 2023
1 min read
| 34 views
Template

In this Vue tip, I want to show you how to use dynamic slot names in Vue.
This can be useful for scenarios like a multi-step form or a table component.
Let's take a look at how you can dynamically generate slots at runtime:
1
<script setup lang="ts">
2
defineProps<{ items: Array<{ id: string; name: string }> }>();
3
</script>
4
5
<template>
6
<div v-for="item in items" :key="item.id">
7
👋
8
<slot :name="item.name" />
9
</div>
10
</template>
In your parent component you can now use the v-slot:[item.name]
syntax to dynamically generate a slot name for each item in the items
array:
1
<script setup lang="ts">
2
import Child from './components/Child.vue';
3
4
const items: Array<{ id: string; name: string }> = [
5
{ id: 1, name: 'Item 1' },
6
{ id: 2, name: 'Item 2' },
7
];
8
</script>
9
10
<template>
11
<Child :items="items">
12
<template v-for="item in items" v-slot:[item.name]>
13
<p>Hello from {{ item.name }}</p>
14
</template>
15
</Child>
16
</template>
Instead of v-slot:[item.name]
you can also use #[item.name]
shorthand.
StackBlitz
Try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Nuxt Tip: Detecting Server vs. Client-Side Code ExecutionSep 29, 2023
Nuxt Tip: How to Fix "Nuxt Instance Unavailable" ErrorOct 12, 2023
Show comments