3👍
Here’s the example how you could solve image switching in vue.
var app = new Vue({
el: "#app",
data() {
return {
index: 0,
image: null,
images: [{
id: 1,
src: "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg",
alt: "Natural Grove Green Trees Path"
},
{
id: 2,
src: "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg",
alt: "stockafbeelding cascades in nationaal park plitvice"
},
{
id: 3,
src: "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg",
alt: "natural view of waterfall"
}
]
}
},
mounted() {
this.switchImage();
},
methods: {
switchImage() {
this.image = this.images[this.index];
this.index = (this.index + 1) % this.images.length;
}
}
});
.image {
width: 100px;
height: 100px;
margin: 2px;
cursor: pointer;
transition: filter 0.3s ease-in;
}
.image:hover {
filter: brightness(1.2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<img v-if="image" :key="image.id" @click="switchImage" class="image" :src="image.src" alt="image.alt">
</div>
1👍
Specify a variable in the component’s data, called image source. Then, write an onClick function, that changes this variable in the data.
Component:
data: () => ({
imageSource: ''
}),
methods: {
changeSource: function() {
//Your source-changing code here
}
}
Template:
<img :src="imageSource" @click="changeSource" />
- [Vuejs]-Vue custom search filter doesn't match with v-model value
- [Vuejs]-Why v-bind parameters cannot reference a variable in an object?
0👍
you need two variables:
data: {
urls: [url1, url2, url3],
currentUrl: this.urls[0]
}
then you add a method which changes the currentUrl
to the next of the array
methods: {
nextUrl: () => {
const currentIndex = urls.findIndex(url => url === currentUrl)
this.currentUrl = urls[currentIndex++]
}
}
in the html you attach everything to the image
<img :src="currentUrl" @click="nextUrl()">
Source:stackexchange.com