Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
},
like image 573
Figar Ali Avatar asked Aug 18 '17 09:08

Figar Ali


1 Answers

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>
like image 179
kevguy Avatar answered Oct 01 '22 08:10

kevguy