반응형
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];
그리고 묶다src
img 요소의 귀속currentBgPath
참조URL: https://stackoverflow.com/questions/45752960/how-to-get-random-element-in-vue-js
반응형
'IT이야기' 카테고리의 다른 글
어떻게 하면 iframes를 백그라운드에서 살려둘 수 있을까? (0) | 2022.03.29 |
---|---|
라우터 + Redex 반응 - 경로 변경 시 비동기 작업을 전송하시겠습니까? (0) | 2022.03.29 |
기능이 소품으로 전달될 때 Array.map의 반응 기능 구성 요소가 항상 리렌더링됨 (0) | 2022.03.29 |
Vuex: REST API에 대한 약속 호출을 사용하여 비동기 작업 처리 (0) | 2022.03.29 |
Vue js 동적 데이터 구성 요소 (0) | 2022.03.29 |