天天看點

vue 中 this.$refs.name.offsetHeight 擷取不到值

通過 vue 動态擷取剩餘區域的滾動高度 中的需求,固定高度如果是一個元件(元件裡使用 v-if )時,我們無法通過之前的方式(this.$refs.name.offsetHeight)擷取到資料,那我們怎麼辦呢?

<template>
  <div class="introduce" v-if="JSON.stringify(entryObj) !== '{}'">
    ...
  </div>
</template>
           

此刻我們可以在子元件mounted鈎子中使用 nextTick,傳遞給父元件。

this.$nextTick(() => { //使用nextTick為了保證dom元素都已經渲染完畢 
  this.$emit('eventGetHeight',this.$el.offsetHeight);
});
           

父元件中監聽eventGetHeight事件,并取得這個資料。

<introduce 
  :entryObj="intrObj" 
  v-show="!dialogShow" 
  @openDialog="open" 
  @eventGetHeight="getHeight" 
  ref="intr"
></introduce>
           

擷取到螢幕高度和固定高度後,我們可以計算出内容區域滾動高度了。

getHeight(data){
  let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
  this.scrollHeight = (clientHeight - data) +'px'
},
           

隻需在内容區域動态設定屬性即可實作。

<div style="overflow-x: hidden; overflow-y: scroll;" :style="{ height: scrollHeight }">
  ...
</div>
           

總結:調用的元件和 v-if 結合使用,且元件的資料是動态的,即高度也是動态的。

ref不是響應式的,所有的動态加載的模闆更新它都無法相應的變化。

通過渲染子元件成功之後(即擷取到動态資料),傳遞給父元件,再進行計算滾動區域。

繼續閱讀