3

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

Jens
  • 5,767
  • 5
  • 54
  • 69
stefano capra
  • 159
  • 5
  • 13
  • 5
    What are you trying to do? The error is pretty explicit. You can't have more than one slot with the same name. – Bert Nov 01 '17 at 20:52
  • Yes, I understand that the error is explicit and I know that it seems not possible do it in that way, and I was wondering if anyone know how to place something like a named slot inside a loop. I'd like to iterate over a loop my data, and place some code in the named slot inside the loop. So, I'd have a parent that pass data to child, which do the iteration, and place a slot where the parent 'can insert' other html code regarding the situation. Hope make sense – stefano capra Nov 01 '17 at 21:20
  • You want to pass something in a slot and render it multiple times? – Bert Nov 01 '17 at 21:43
  • Something like this? https://codepen.io/Kradek/pen/vWNdaN?editors=1010 – Bert Nov 01 '17 at 21:51
  • Yes, I have this div inside child component that repeat itself using v-loop directive. Inside this div, regarding the situation, I 'd like to place either a span or a button for example, and the only way I thought would have been possible is to place a slot inside the loop. Do you know how to do that? Maybe with other methods – stefano capra Nov 01 '17 at 21:53
  • Sorry I had a link I forgot to paste. Take a look at it above. – Bert Nov 01 '17 at 21:54
  • Yes, that's exactly what I need. Do you also know a way to do without using the render function? Or it's the only way to add slots "financially"? Anyway, thank you for the hint – stefano capra Nov 01 '17 at 22:02
  • I don't know of a way without a render function off the top of my head. – Bert Nov 01 '17 at 22:35

1 Answers1

6

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>
Florian Haider
  • 1,892
  • 18
  • 23