How to display a random image in Vue.js

in Code Write a comment

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: [

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: [
    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.

Hi, I'm Renat 👋


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>

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. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other Vue.js tutorials, e.g. how to pass data to a component in Vue.js.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment