Home > Software design >  How to make carousel with Vue?
How to make carousel with Vue?

Time:11-10

Problem: I'm trying to make a carousel slider animation with Vue, where upon clicking "next" a "slide-forward" animation is going to be played, and upon "prev" - "slide-back" animation. Despite all attempts, I still get this very strange behaviour. Will really appreciate if anybody can put me on the right track here: 1

My approach:

<template>
    <div >
      <div v-for="(slide, index) in slides" :key="slide.id">
        <transition :name="back ? 'slideback' : 'slide'">
          <div  v-if="index === currentIndex">{{ slides[currentIndex]['name'] }}</div>
        </transition>
      </div>
    </div>
    
    <div >
        <button @click="moveSlide(-1)" >prev</button>
        <button @click="moveSlide(1)">next</button>
    </div>
</template>

<script>
export default {
    data () {
        return {
            slides: [
                {name:'akml;ll;m;l'},
                {name:'bwerrrrrrrrrrrr'},
                {name:'werwerwrwwrc'}
            ],
            back: false,
            currentIndex: 0
        }
    },
    methods: {
        moveSlide(offset) {
            this.back = offset < 0
            console.log(this.back)
            let temp_index = this.currentIndex   offset
            this.currentIndex = temp_index >= this.slides.length ? 0 : temp_index < 0 ? this.slides.length - 1 : temp_index
        },
    },
}
</script>

<style scoped>
.slide-leave-active,
.slide-enter-active {
  transition: 1s;
}
.slide-enter {
  transform: translate(100%, 0);
}
.slide-leave-to {
  transform: translate(-100%, 0);
}

.slideback-leave-active,
.slideback-enter-active {
  transition: 1s;
}
.slideback-enter {
  transform: translate(-100%, 0);
}
.slideback-leave-to {
  transform: translate(100%, 0);
}
</style>

CodePudding user response:

Problem was related to me using a Vue 2 class for entering animation mode instead of the one from Vue 3. I just followed the migration tips here and now everything works as intended: https://v3-migration.vuejs.org/breaking-changes/transition.html

  • Related