<script>
export default {
name: "Slider",
data() {
return {
images: [
"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg",
"https://cdn.pixabay.com/photo/2016/02/17/23/03/usa-1206240_1280.jpg",
"../assets/sample-1.jpg"
"https://cdn.pixabay.com/photo/2016/12/04/19/30/berlin-cathedral-1882397_1280.jpg"
],
currentIndex: 0
};
},
methods: {
next: function() {
this.currentIndex += 1;
},
prev: function() {
this.currentIndex -= 1;
}
},
computed: {
currentImg: function() {
return this.images[Math.abs(this.currentIndex) % this.images.length];
}
}
};
</script>
vue.js below
<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>
Just scrolls to the top every time i click on either prev or next can't figure out why. Also i havent been able to get any of my own images from assets to appear in the slider and not sure why it isnt able to retrieve them this way (as in the sample-1.jpg) Thanks.
href="#"v-for or transition-group. A simple transition with mode="out-in" is enough. You put the key to the current image, so vue always knows if the image gets replaced so it can do a transitionDont put images into the assets folder. You better put it into the static folder.
Then you can access your image like /sample-1.jpg
new Vue({
name: "Slider",
el: "#app",
data() {
return {
images: [
"https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg",
"https://cdn.pixabay.com/photo/2016/02/17/23/03/usa-1206240_1280.jpg",
"/sample-1.jpg",
"https://cdn.pixabay.com/photo/2016/12/04/19/30/berlin-cathedral-1882397_1280.jpg"
],
currentIndex: 0
};
},
})
.v-enter-active,
.v-leave-active {
transition: opacity 1s ease;
}
.v-enter,
.v-leave-to {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<a class="prev" @click="currentIndex--" v-if="currentIndex > 0">❮ Previous</a>
<a class="next" @click="currentIndex++" v-if="currentIndex < images.length - 1">❯ Next</a>
<transition name="v" mode="out-in">
<img :key="images[currentIndex]" :src="images[currentIndex]" />
</transition>
</div>