Let's take a look at this simple exercise in VueJS, wherein we will create a simple Image changer.
Consider the screenshot below, Here is how the image changer looks like.
We show the image and along with that, we also show the Previous and Next button below that. Here are the application requirements
- By default, the app should show the first image, with the previous button disabled.
- Clicking on the next button should show the next button in the images array until we reach the last image.
- On reaching the last image the Next button should get disabled.
- On reaching back to the first image, the previous button should get disabled.
Consider the Vue Instance with the following data properties.
var app = new Vue({
el: '#app',
data: {
images: [
'https://i.imgur.com/rmydi2w.jpg',
'https://i.imgur.com/rAFqZiM.jpg',
'https://i.imgur.com/Fpw5KKY.jpg',
'https://i.imgur.com/IbYRmoW.jpg',
'https://i.imgur.com/9poVrgA.jpg'
],
currentImage : 0
},
...
});
We have defined an images
array which contains the external URL's of all the images.
Also, we have defined another data property named currentImage
which denotes the current position of Image, which by default is 0.
Now in the HTML, here is how we show the default first image along with Previous and Next Buttons.
<div id="app" class="text-center">
<img :src="images[currentImage]" width="400" height="500"><br/><br/>
<button class="btn btn-primary">Previous</button>
<button class="btn btn-primary">Next</button>
</div>
Changing Image
Next Up, Let's write the necessary methods, that will be invoked on the click event of the next and previous buttons.
<button class="btn btn-primary">Previous</button>
<button class="btn btn-primary">Next</button>
...
...
methods:{
nextImage: function(e){
if(this.currentImage !== (this.images.length -1))
this.currentImage++;
},
previousImage: function(e){
if(this.currentImage !== 0)
this.currentImage--;
}
}
nextImage
: This method increment the currentImage
counter by 1 until we reach the end of the array.
previousImage
: This method decrements the currentImage
counter by 1 until we reach the first image.
Disabling Buttons
We need to disable the Next button when we reach the end of the images array and we need to disable the previous button once we reach the start of the array.
<button @click="previousImage" class="btn btn-primary" :disabled="currentImage === 0">Previous</button>
<button @click="nextImage" class="btn btn-primary" :disabled="currentImage === (images.length - 1)">Next</button>
We have used the shorthand for v-bind
directive to add disabled if the condition defined is true.
[WP-Coder id="2"]