stefano capra
stefano capra

Reputation: 159

Insert named slot inside v-for loop vuejs

Does anyone know how to insert a named slot inside a loop? I've got for example this code: Children

<div v-for="num in nums" :key="num">
    <slot name="foo"></slot>
</div>

And the parent is like:

<foo-component :nums="nums>
    <template slot="foo">
        <span>Inside the foo component</span>
    </template>
</foo-component>

If I do so, the console will show this alert:

Duplicate presence of slot "foo" found in the same render tree - this will likely cause render errors.

Does anyone know how to accomplish that?
Thanks in advance

Upvotes: 3

Views: 5687

Answers (1)

Florian Haider
Florian Haider

Reputation: 1912

Slot names have to be unique. If you want to create slots inside a loop, you can add a number to the slot name, e.g.:

<div v-for="num in nums" :key="num">
    <slot :name="'foo_' + num"></slot>
</div>

And then use them like this:

<foo-component :nums="3">
    <template slot="foo_1">
        <span>Inside the foo component slot 1</span>
    </template>
    <template slot="foo_2">
        <span>Inside the foo component slot 2</span>
    </template>
    <template slot="foo_3">
        <span>Inside the foo component slot 3</span>
    </template>
</foo-component>

Upvotes: 6

Related Questions