vuejs image carousel using transition component and composition api in javascript

Here's an example of an image carousel built with Vue.js using the Composition API and the Transition component:

<template>
  <div class="carousel-container">
    <transition name="fade">
      <img :src="currentImage" :key="currentImage" class="carousel-image">
    </transition>
    <div class="carousel-buttons">
      <button @click="previousImage">Previous</button>
      <button @click="nextImage">Next</button>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const images = [
      'https://via.placeholder.com/500x500?text=Image+1',
      'https://via.placeholder.com/500x500?text=Image+2',
      'https://via.placeholder.com/500x500?text=Image+3'
    ];

    const currentImageIndex = ref(0);

    const currentImage = computed(() => {
      return images[currentImageIndex.value];
    });

    const previousImage = () => {
      currentImageIndex.value--;
      if (currentImageIndex.value < 0) {
        currentImageIndex.value = images.length - 1;
      }
    };

    const nextImage = () => {
      currentImageIndex.value++;
      if (currentImageIndex.value >= images.length) {
        currentImageIndex.value = 0;
      }
    };

    return {
      currentImage,
      previousImage,
      nextImage
    };
  }
};
</script>

<style>
.carousel-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
}

.carousel-image {
  width: 500px;
}

.carousel-buttons {
  display: flex;
  justify-content: space-evenly;
  margin-top: 1rem;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
1558 chars
81 lines

In this example, we create a images array that holds the URLs for the images we want to display. We also define a currentImageIndex ref that keeps track of the current image being shown.

We use the computed function from the Composition API to generate a currentImage computed property that returns the URL for the current image based on the currentImageIndex ref.

We then define two methods, previousImage and nextImage, that update the currentImageIndex ref accordingly.

Finally, we use the transition component from Vue.js to add a fade effect when the image changes. The fade effect is defined in the CSS with a combination of classes (fade-enter, fade-leave-to, etc.) that are added and removed automatically by Vue.js when the component is mounted, updated or unmounted.

gistlibby LogSnag