In this tutorial, you’ll learn how to randomly select an image path from an array and display it.
Let’s create our array of image paths in the data object. We’ll be using Lorem Picsum service to generate placeholders.
images: [
'https://picsum.photos/600/200',
'https://picsum.photos/600/200',
'https://picsum.photos/600/200'
]
Generate a random image in Vue.js example
We’ve got 3 images in our images
array. Now let’s create an ES6 function that will select a random item from an array.
new Vue({
el: "#app",
data: {
images: [
'https://picsum.photos/600/200',
'https://picsum.photos/600/200',
'https://picsum.photos/600/200'
],
selectedImage: null
},
methods: {
randomItem (items) {
return items[Math.floor(Math.random()*items.length)];
}
},
created() {
this.selectedImage = this.randomItem(this.images)
}
})
randomItem()
method returns a random item from an array passed to this function. We pass an array of images to this function and it will return a random image.
Since we don’t need to access DOM yet, we can generate a random image by calling a andomItem()
method inside the computed()
hook. Remember the Vue.js lifecycle hooks?
created() {
this.selectedImage = this.randomItem(this.images)
}
The code above will set a randomly generated image to the selectedImage
variable.
HTML part
Now we can display a random image each time component loads.
<div id="app">
<h2>Random image in Vue.js:</h2>
<p v-if="selectedImage"><img style="width:100%" :src="selectedImage" alt=""></p>
</div>
This will output to:
Alternatively, you can manually generate a random image by clicking on the “Generate random image” button.
If you find this post useful, please let me know in the comments below and subscribe to my newsletter.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/random-image-vue-js
PS: Make sure you check other Vue.js tutorials, e.g. how to pass data to a component in Vue.js.