IT이야기

Vue.js에서 임의 요소를 가져오는 방법

cyworld 2022. 3. 29. 21:50
반응형

Vue.js에서 임의 요소를 가져오는 방법

나는 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();
},

모든 것이 꽤 직진적이다.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>

이렇게 하면 된다.

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];
    }
})
  • 이미지 경로를 데이터 속성의 배열로 초기화

  • 데이터 속성을 초기화하다currentBgPath그리고 null로 설정됨

  • 생성된 수명 주기 후크에서 이미지 경로 배열의 항목 수 내에서 임의의 수를 얻음

    var random = Math.floor(Math.random() * this.heroBgPaths.length);
    
  • 의 가치를 정하다currentBgPath사용.this.currentBgPath = this.heroBgPaths[random];그리고 묶다srcimg 요소의 귀속currentBgPath

참조URL: https://stackoverflow.com/questions/45752960/how-to-get-random-element-in-vue-js

반응형