Tryin to build a simple custom image slide and mostly make it work except one thing. When :src data changes, I want to add a transition like opacity:0 ~ 1 but couldn’t achieve that part. Here is the slide.
template
<img class="slide-image" :src="getImgUrl(images[0])">
script
data(){
return {
images: [
"/images/home/home-slide1.png",
"/images/home/home-slide2.png",
"/images/home/home-slide3.png",
"/images/home/home-slide4.png",
"/images/home/home-slide5.png",
]
};
},
watch: {
getImgUrl(){
}
},
mounted(){
window.setInterval(()=>{
this.slide();
}, 5000);
},
methods: {
getImgUrl(im) {
return require('../assets' + im)
},
slide(){
let first = this.images.shift();
this.images = this.images.concat(first);
},
},
what is best and simple possible way to add a transition when :src changes every 5s, appreciate if anyone can guide about this.
Advertisement
Answer
<script>
export default {
name: "Slider",
data() {
return {
images: [
"/images/home/home-slide1.png",
"/images/home/home-slide2.png",
"/images/home/home-slide3.png",
"/images/home/home-slide4.png",
"/images/home/home-slide5.png",
],
timer: null,
currentIndex: 0
};
},
mounted: function() {
this.startSlide();
},
methods: {
startSlide: function() {
this.timer = setInterval(this.next, 5000);
},
next: function() {
this.currentIndex += 1;
},
prev: function() {
this.currentIndex -= 1;
}
},
computed: {
currentImg: function() {
return this.images[Math.abs(this.currentIndex) % this.images.length];
}
}
};
</script>
Let’s look what we did here:
- We got an array of image URLs.
- Set
timerto null and setcurrentIndexto 0 for showing the first image. - Created
startSlidefunction for sliding images every 4 seconds. - Created
nextandprevfunctions for sliding to the previous or the next image. According to the lastcurrentImgfunction it detects which image must show at that time based on the index.
HTML:
<template>
<div>
<transition-group name="fade" tag="div">
<div v-for="i in [currentIndex]" :key="i">
<img :src="currentImg" />
</div>
</transition-group>
<a class="prev" @click="prev" href="#">❮ Previous</a>
<a class="next" @click="next" href="#">❯ Next</a>
</div>
</template>
Here we take advantage of the built-in transtion-group component that comes with Vue.js, then iterate images and add the functions we created earlier.
More details here: https://alligator.io/vuejs/create-image-slider/