ยท
1 min read

Vue Tip: Dynamic Slot Names

MH

Michael Hoffmann

@mokkapps

Vue Tip: Dynamic Slot Names Image

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:

Child.vue
<script setup lang="ts">
defineProps<{ items: Array<{ id: string; name: string }> }>();
</script>

<template>
  <div v-for="item in items" :key="item.id">
    ๐Ÿ‘‹
    <slot :name="item.name" />
  </div>
</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:

Parent.vue
<script setup lang="ts">
import Child from './components/Child.vue';

const items: Array<{ id: string; name: string }> = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
];
</script>

<template>
  <Child :items="items">
    <template v-for="item in items" v-slot:[item.name]>
      <p>Hello from {{ item.name }}</p>
    </template>
  </Child>
</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 BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :

I will never share any of your personal data. You can unsubscribe at any time.