Reputation: 660
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.
Upvotes: 1
Views: 5037
Reputation: 1544
You can try the Vue-transition
Wrap your transition section with transition
tag like this
<transition name="slider">
<img class="slide-image" :src="getImgUrl(images[0])">
</transition>
It will add classes when the elements enter and leave. So you can add styles accordingly.
Please refer this link : https://v2.vuejs.org/v2/guide/transitions.html#Transitioning-Single-Elements-Components
Upvotes: 0
Reputation: 2209
<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:
timer
to null and set currentIndex
to 0 for showing the first image.startSlide
function for sliding images every 4 seconds.next
and prev
functions for sliding to the previous or the next image. According to the last currentImg
function 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/
Upvotes: 2