[Vue.js/Nuxt.js] Element 높이 값 받아오기

ehye·2020년 9월 16일
0
post-thumbnail

노란색 동그라미 부분이 내용에 따라 높이가 변화한다

그렇기 때문에
노란색 동그라미 부분이 변함에 따라 빨간 박스도 높이값이 변화

알고 싶은 것:

보라색 상자 높이 값!

빨간색 상자 높이 값을 구한 다음, 파란 부분 차이를 더해서 보라색 박스 높이 값을 구하려 한다

이를 위해서 빨간색 박스의 높이 값을 받아와야 한다

vue 에서 DOM 에 접근하기 위해서는 $refs 를 사용할 수 있다


  <div class="wrap">
    
   // 보라색 상자
    <section class="purple">
        <div class="background_pic"></div>
    </section>


    // 빨간 상자
    <section class="red" ref="red_height">
      // 프로필 사진
      <div class="carrot"></div>
     // 사용자 정보
      <div class="info"></div>

    </section>

</div>

와 같은 구조라고 가정

  • 보라색 박스 높이 구하기 ()

export default {

    data() {
      return {
        red_box_height:'',
        purple_height:'',
      }
    }
}

methods: {
      getInfoHeight () {
        let val  = this.$refs.red_height.scrollHeight;
        // red_height 의 높이값 받아온다
        this.red_box_height = `${val}px`;
        // red_box_height 에서 
        // "background img 높이 - 프로필 사진 차지한 값" 더한다 
        // (= background img 높이 - 초록색 부분 높이 = 파란 부분 높이) 
        // 10px 라고 가정
        // 더하고 밑에 넉넉히 10px 마진 줌
        this.purple_height = `${this.red_box_height} + 10px + 30px`

      },

               
// dom 에 접근하기 위해 mounted 에 method 사용
        
mounted(){
	this.getInfoHeight()
},
        
  • template 부분에 binding 해주기

  <div class="wrap">
    
   // 보라색 상자
    <section class="purple" :style="`height:calc(${purple_height}`">
        <div class="background_pic"></div>
    </section>


    // 빨간 상자
    <section class="red" ref="red_height">
      // 프로필 사진
      <div class="carrot"></div>
     // 사용자 정보
      <div class="info"></div>

    </section>

</div>
profile
*잘못된 점이 있으면 언제든지 알려주세요 =)

0개의 댓글