2017-12-25 20 views
0

너비가 50 % 인 이미지가 있습니다.동적 스타일을 사용하여 너비를 기준으로 한 이미지 높이 설정

<img :src="post.image" ref="image" :style="{ height: imageHeight + 'px' }" /> 

imageHeight() { 
      let image = this.$refs.image 
      if(!image) return 0 
      let height = image.clientWidth * 0.5 
      return height 
     } 

불행히도 이미지는 imageHeight의 평가시에 정의되지 그것은 때 폭의 변화를 재평가되지 않습니다. 감시자 또는 다른 방법으로 작동하도록 할 수있는 방법이 있습니까?

답변

1

load event을 사용하여 변수를 설정할 수 있습니다. 계산 된 데이터를 사용하고있는 것처럼 보이지만 데이터가 변경되지 않습니다.

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    url: 'http://via.placeholder.com/200x200', 
 
    imageHeight: null 
 
    }, 
 
    methods: { 
 
    setheight(event) { 
 
     let image = event.target; 
 
     this.imageHeight = image.clientWidth * 0.5; 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> 
 
<div id="app"> 
 
    <img :src="url" @load="setheight" :style="{ height: imageHeight + 'px' }"> 
 
    <div>{{imageHeight}}</div> 
 
</div>