vuejs image carousel using transition component in javascript

To create an image carousel using Vue.js transition component, you can follow these steps:

  1. Create a component for the image carousel
index.tsx
<template>
  <div class="carousel">
    <transition name="slide">
      <img v-bind:src="currentImage" key="currentImage">
    </transition>
    <button @click="previousImage">Previous</button>
    <button @click="nextImage">Next</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      images: [
        "https://example.com/image1.jpg",
        "https://example.com/image2.jpg",
        "https://example.com/image3.jpg",
        "https://example.com/image4.jpg",
      ],
      currentIndex: 0,
    };
  },
  computed: {
    currentImage() {
      return this.images[this.currentIndex];
    },
  },
  methods: {
    previousImage() {
      this.currentIndex =
        (this.currentIndex + this.images.length - 1) % this.images.length;
    },
    nextImage() {
      this.currentIndex = (this.currentIndex + 1) % this.images.length;
    },
  },
};
</script>

<style>
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.5s;
}
.slide-enter,
.slide-leave-to {
  transform: translateX(100%);
}
</style>
1047 chars
51 lines
  1. In the component above, we used the transition component for animating the slide effect. We specified the name attribute to "slide", which will be the class name used for the CSS animation.

  2. We also defined a computed property for the currentImage. This will return the image URL for the current index.

  3. We used the methods for previousImage and nextImage to update the currentIndex property.

  4. Finally, we defined styles for the slide effect animation. We set the transition property for the .slide-enter-active and .slide-leave-active classes, and set the transform property for the .slide-enter and .slide-leave-to classes.

You can use this component in your Vue.js application by importing it and adding it to your template with <Carousel />.

gistlibby LogSnag