vuejs image carousel left and right transition animation in javascript

To create an image carousel in Vue.js with left and right transition animations, we can use the following approach.

Assuming that we have a list of images in our Vue component data, we can create a div container that will hold the images, using the v-for directive to iterate over the list of images.

<template>
  <div class="carousel">
    <div class="slides">
      <div v-for="(image, index) in images" :key="index">
        <img :src="image.src" :alt="image.alt">
      </div>
    </div>
  </div>
</template>
212 chars
10 lines

We can then add some styling to the container and slides to make them visible and stack the images on top of each other.

.carousel {
  position: relative;
  width: 100%;
  overflow: hidden;
  height: 400px;
}

.slides {
  display: flex;
  height: 100%;
  width: 100%;
  transition: transform 0.5s ease-in-out;
}
191 chars
14 lines

To create the left and right transition animations, we can add two buttons to the component and use a data property to track the current index of the image being shown.

<template>
  <div class="carousel">
    <div class="slides" :style="{ transform: slideTransform }">
      <div v-for="(image, index) in images" :key="index">
        <img :src="image.src" :alt="image.alt">
      </div>
    </div>
    <button @click="previousSlide">Prev</button>
    <button @click="nextSlide">Next</button>
  </div>
</template>
345 chars
12 lines
index.tsx
export default {
  data() {
    return {
      currentIndex: 0,
      images: [
        {
          src: 'path/to/image1.jpg',
          alt: 'Image 1'
        },
        {
          src: 'path/to/image2.jpg',
          alt: 'Image 2'
        },
        {
          src: 'path/to/image3.jpg',
          alt: 'Image 3'
        }
      ]
    }
  },
  computed: {
    slideTransform() {
      return `translateX(-${this.currentIndex * 100}%)`;
    }
  },
  methods: {
    previousSlide() {
      this.currentIndex = (this.currentIndex === 0) ? this.images.length - 1 : this.currentIndex - 1;
    },
    nextSlide() {
      this.currentIndex = (this.currentIndex === this.images.length - 1) ? 0 : this.currentIndex + 1;
    }
  }
}
728 chars
35 lines

The slideTransform method uses the currentIndex to calculate the translate value for the slides container, which will shift it left or right depending on the current index.

The previousSlide and nextSlide methods simply decrement or increment the currentIndex, wrapping around if it reaches the ends of the image list.

With this solution, we can create an image carousel with left and right transition animations in Vue.js using JavaScript.

gistlibby LogSnag