How to get index in Vue slots

430 Views Asked by At

In the parent component I render a Carousel component (child component) and pass the content of the slot inside.

Inside the carousel component, I want to get the index of the slot content and pass it to run a function changeSlide(index). How can I get the index of the passed content from inside the <slot>?

Parent Component

<Carousel>
  <template #menu="{onChangeSlide}">
    <template v-for="(label, index) in args.testLabel" :key="index">
      <Button @click="onChangeSlide" :label="label" :index="index" />
    </template>
  </template>
</Carousel>

Carousel component

<template>
  <div>
    <slot
      name="menu"
      :on-change-slide="() => changeSlide(index)". //Want to get the index of the content here
    />
  </div>
</template>
1

There are 1 best solutions below

0
user16589580 On

In the end I was able to do it like this.

I changed @click="onChangeSlide" to @click="onChangeSlide(index)" in the parent but also had to change :on-change-slide="() => changeSlide(index)" to :on-change-slide="changeSlide" in the carousel component.

Parent component

<Carousel>
  <template #menu="{onChangeSlide}">
    <template v-for="(label, index) in args.testLabel" :key="index">
      <Button @click="onChangeSlide(index)" :label="label" :index="index" />
    </template>
  </template>
</Carousel>

Carousel component

<template>
  <div>
    <slot
      name="menu"
      :on-change-slide="changeSlide"
    />
  </div>
</template>