Dave851
Dave851

Reputation: 37

Vuetify v-carousel multiple components

I want to display the carousel component inside multiple components. That's my carousel component:

<template>
<v-container>
    <v-carousel>
        <v-carousel-item v-for="image in images" 
                         :key="image.alt" 
                         :src="image.src" 
                         :alt="image.alt">
        </v-carousel-item>
    </v-carousel>

This component is inside my other components where i want to show this carousel. Inside each components i have one array of objects with all my images i want to display How can i pass these images through my carousel component?

What's the best way to do this? I hope it's clear, i just started to study vue

Thank you very much

Upvotes: 0

Views: 3877

Answers (1)

Jess
Jess

Reputation: 3146

You'll add a property called "images" to your carousel component in the script block. Then, you'll use the component elsewhere.

Carousel Component:

<template>
<v-container>
    <v-carousel>
        <v-carousel-item v-for="image in images" 
                         :key="image.alt" 
                         :src="image.src" 
                         :alt="image.alt">
        </v-carousel-item>
    </v-carousel>
</v-container>
</template>

<script>
export default {
  props: {
    images: {
      type: Array,
      // Arrays and Objects must return factory functions instead of
      // literal values. You can't do `default: []`, you have to do
      // `default: function() { return []; }`... what I wrote was the 
      // short-hand for how to do it with ES6 fat-arrow functions
      default: () => ([]) 
    }
  }
}
</script>

And you can now use the carousel elsewhere...

<template>
  <div>
    My beautiful carousel: <my-carousel :images="myImages"/>
  </div>
</template>

<script>
import MyCarousel from './MyCarousel.vue'
export default {
  components: { MyCarousel }, // "MyCarousel" converts to either camelcase or title case (my-carousel || MyCarousel)
  data() {
    return {
      myImages: [{ alt: 'A kitten', src: 'http://placekitten.com/200/300' }]
    }
  }
}
</script>

Upvotes: 1

Related Questions