如何在Vue.js中获取随机元素

7

我有3张英雄图片和它们的内容,希望在用户刷新页面时随机显示其中一张!

基本上,我想在加载页面时使用jQuery显示随机div,但问题在于英雄图片的大小较大,通过Jquery,这3个图片都开始在DOM中加载,这会影响页面速度。

在Vue.js中是否有解决方案,只在用户刷新页面时加载一个特定的div,而不是全部3个divs!?

<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代码:

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

那些图片是什么?它们是数据URL还是只是图像链接?而且你只显示了一张图片,不是全部三张,对吧? - kevguy
@kevlai22 是的,想要在 DOM 中随机显示一个,这是 HTML 代码。<div class="slider-item"> <img src="../../../static/img/slides/slide1.png" alt="Hello"> <div class="carousel-caption"> <h2>Lipsum 标题</h2> <h4>Lipsum 虚拟内容正文测试占位符。</h4> </div> </div> - Figar Ali
2个回答

9

一切都很简单。只需在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>


关于这个小问题:数据需要是一个函数。也就是说,它应该是: data() { return {} } - Callum Flack
1
在组件中,是的,在上面的代码中,这并不是必要的。 - kevguy
好的,没注意到 @kevguy - Callum Flack

1
你可以像这样做:

html

<div id="hero-bg">
    <img :src="currentBgPath">
</div>
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接