Figar Ali
Figar Ali

Reputation: 866

How to get random element in Vue.js

I have 3 hero images and their content and I want to display them randomly when user refreshes the page!

Basically I am trying to display random div using Jquery on loading page, but issue is that the size of hero image is large and by using Jquery, all these 3 images start loading in DOM which affects the speed of page.

Is there any solution for this in Vue.js for loading that one specific div at a time, not all 3 divs when user refreshes the page!?

<div class="slider-item"> <img src="../../../static/img/slides/slide1.png" alt="Hello"> 
       <div class="carousel-caption"> 
           <h2>Lipsum Heading</h2> 
               <h4>Lipsum dummy content body test dummy goes here.</h4> 
       </div> 
   </div>

jQuery Code:

mounted()
{
 var random = Math.floor(Math.random() * $('.slider-item').length);
 $('.slider-item').eq(random).show();
},

Upvotes: 7

Views: 16232

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

You can do it like this:

html

<div id="hero-bg">
    <img :src="currentBgPath">
</div>

script

new Vue({
    el: '#hero-bg',
    data:{
        heroBgPaths: [
            '../path/to/img1',
            '../path/to/img2',
            '../path/to/img3'
        ],
        currentBgPath: null
    },
    created(){

        var random = Math.floor(Math.random() * this.heroBgPaths.length);
        this.currentBgPath = this.heroBgPaths[random];
    }
})
  • initialize the paths to your images as an array in your data property

  • initialize a data property currentBgPath and set to to null

  • in created life cycle hook get a random number within the number of items in your image paths array using

    var random = Math.floor(Math.random() * this.heroBgPaths.length);
    
  • set the value of currentBgPath using this.currentBgPath = this.heroBgPaths[random]; and bind the src attribite of the img element to currentBgPath

Upvotes: 1

kevguy
kevguy

Reputation: 4438

Everything is pretty straight forward. Just randomize the link you've chosen in Vue.

const app = new Vue({
  el: '#app',
  data: {
    images: [
      'http://via.placeholder.com/350x150',
      'http://via.placeholder.com/200x140',
      'http://via.placeholder.com/200x100'
    ],
    selectedImage: ''
  },
  created () {
    const idx = Math.floor(Math.random() * this.images.length);
    this.selectedImage = this.images[idx]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <img v-bind:src="selectedImage" />
</div>

Upvotes: 9

Related Questions