Hello guys,
Im trying to build a simple carousel slider in vue 2.
First problem is that my timeline is initially paused (i heard that is a good practice) and if i click next or prev button my animation doesn't play.
I found solution, but I don't know if it is right one.
I mean, it works but when using prevSlide function animation back to first initial slide. (probably thats another not related problem)
So my question is how to handle timelines in vue.
Should I put timeline in mounted, and prevSlide and nextSlide functions should only play or reverse the timeline?
temporary solution:
nextSlide() {
this.tl.to(gsap.utils.toArray(this.$refs.slider.children), {
xPercent: "-=" + 100,
onComplete: this.tl.pause()
});
this.tl.play()
}
the main code:
<template>
<div id="app">
<div class="slider" ref="slider">
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
</div>
<button @click="prevSlide">prev</button>
<button @click="nextSlide">next</button>
</div>
</template>
<script>
import gsap from "gsap";
export default {
name: "App",
data() {
return {
currSlide: 1,
tl: gsap.timeline({ paused: true }),
};
},
methods: {
nextSlide() {
this.tl.to(gsap.utils.toArray(this.$refs.slider.children), {
xPercent: "-=" + 100,
});
},
prevSlide() {
this.tl.to(gsap.utils.toArray(this.$refs.slider.children), {
xPercent: "-=" - 100,
});
},
},
mounted() {},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.slider {
width: 600px;
height: 350px;
display: flex;
flex-direction: row;
overflow: hidden;
}
.slide {
width: 100%;
height: 100%;
flex-shrink: 0;
}
.slide:nth-child(1) {
background: crimson;
}
.slide:nth-child(2) {
background: green;
}
.slide:nth-child(3) {
background: darkcyan;
}
</style>
Code playground down below
https://codesandbox.io/s/gracious-fog-y4b8d?file=/src/App.vue