3

I am trying to use multiple carousel components inside card components with nested v-for loops but I’m having trouble figuring out the correct way to assign the carousel v-model so that it’s unique and doesn’t update all the carousels when the slide is changed which is what I currently have, Here is the code I have so far:

<q-card
    v-for="(item, index) in inventory"
    :key="index"
    style="width: 20rem;"
  >
    <q-card-section
      class="q-pa-none text-white"
    >
      <q-carousel
        animated
        arrows
        navigation
        infinite
        style="height: 15rem;"
        v-model="slide" // What should this be assigned so that
      >
        <q-carousel-slide
          v-for="(image, index) in item.images"
          :key="index"
          :name="index" //It works with the slide name and only updates the respective q-carousel
          :img-src="image.url"
        >
        </q-carousel-slide>
      </q-carousel>
    </q-card-section>
  </q-card>

slide is simply a data prop assigned to 0, this works but when I change the slide of one carousel all of the carousels change too. Hopefully this makes sense, It’s a bit hard for me to explain it but let me know anything that needs clarification

Edit: Dropped the code in codepen here is the link: https://codepen.io/launchit-studio/pen/jOVrKzQ The issue I am having is that the v-model affects all of the carousel slides not just the one that is clicked. I understand this is because the slide prop is shared by all the carousels but I am not sure of what to use in order for it to be 'independent'

1 Answers1

1

Instead of using a single model slide for all the slides, use an array of models. (An object would work too).

data() {
  return {
    slide: 1,   ❌
    activeSlides: []  ✅
  }
}

The index of the carousel in the v-for will also be used as the index in the array:

<q-carousel
  animated
  arrows
  navigation
  infinite
  style="height: 15rem;"
  v-model="activeSlides[index]"
>

Since each carousel's model needs to start at 1, you can initialize activeSlides accordingly:

created() {
  const numCarousels = this.inventory.length;
  this.activeSlides = Array(numCarousels).fill(1);
},

Here is the updated CodePen.

Dan
  • 59,490
  • 13
  • 101
  • 110