Search code examples
javascriptvue.jsvuejs2background-image

Giving random background images to each div in the for loop in Vue Js


I have a v-for loop that runs on a div and gives out a bunch of tags. I need each of those tags to have a different src. Everything that I have tried so far results in all the tags getting the same source. Is there any way I can do this?

<div class="wrapper" v-for="result in results" :key="result.index">
         <div class='small-card'>
            <img class="thumbnail" :src="backgroundImage">
            <div class="text-elements">
               <span class="md-display-2 minicard-title">{{result.name}}</span>
               <br class="break">
               <span class="md-display-1 minicard-subtitle">{{result.state}}</span>
            </div>
         </div>
         <br class="br3">
      </div>

Solution

  • I recently did this in a project.

    What I ended up doing was setting the style tag for background-image using the :style attribute.

    Depending on how you are acquiring the image source, you will need to either create a method to return a random image URL, or access the image URL provided in the object. As you said "random" I assume the first approach would be the best fit.

    Here's a very rough and untested example:

    <template>
      <div>
        <div
          v-for="index in 10"
          :key="index"
          :style="{'background-image': randomImage()}"
        />
      </div>
    </template>
    
    <script>
    export default {
      name: 'Example',
      data() {
        return {
          images: ['1.jpg', '2.jpg', '3.jpg', '4.jpg'],
        };
      },
      methods: {
        randomImage() {
          return `url("${
            this.images[Math.floor(Math.random() * this.images.length)]
          }")`;
        },
      },
    };
    </script>
    

    Make sure that the :style="{'background-image': randomImage()}" contains a () to ensure the method is called vs being referenced.