Creating a carousel component in Vue 3 that accepts items through slots gives you a flexible and reusable carousel. Let's start by creating a simple, functional carousel component. This component will allow you to slot in any content you want for each slide of the carousel.
Step 1: Setup Your Vue 3 Project
If you haven't already, create a new Vue 3 project:
npm install -g @vue/cli
vue create my-vue-project
cd my-vue-project
Choose the default Vue 3 preset or configure it as you like.
Step 2: Create the Carousel Component
Create a new file for your carousel component, let’s call it Carousel.vue, and save it in the src/components directory.
<!-- src/components/Carousel.vue -->
<template>
<div class="carousel">
<button @click="prev">Prev</button>
<div class="carousel-content">
<slot :active="active"></slot>
</div>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
name: 'Carousel',
data() {
return {
active: 0,
};
},
methods: {
next() {
this.active = (this.active + 1) % this.$slots.default().length;
},
prev() {
this.active = (this.active + this.$slots.default().length - 1) % this.$slots.default().length;
},
},
};
</script>
<style>
.carousel-content {
display: flex;
overflow: hidden;
}
</style>
Step 3: Using the Carousel Component
Now, let's use the Carousel component and slot in some items. You might want to create another component for the carousel items or you can directly use HTML elements. For simplicity, we’ll use div elements here.
Open your App.vue or any component where you want to use the carousel and update it as follows:
<template>
<Carousel>
<template v-slot:default="{ active }">
<div v-if="active === 0">Slide 1 Content</div>
<div v-if="active === 1">Slide 2 Content</div>
<div v-if="active === 2">Slide 3 Content</div>
</template>
</Carousel>
</template>
<script>
import Carousel from '@/components/Carousel.vue';
export default {
name: 'App',
components: {
Carousel,
},
};
</script>
Explanation
- This carousel component works by showing/hiding slides based on the
active index.
- The
next and prev button methods update the active index, and only the content with the matching index will be displayed.
- By using a slot with a scoped property (
active), the parent component (App.vue) can control which slide to show based on the active index.
Improvement
For a better user experience and more features (like animations, touch support, dynamic slide addition/removal), you might consider using a library or framework dedicated to carousels, such as Vue Slick Carousel or Swiper, which are highly customizable and come with a rich set of features out of the box.