天天看點

vue 中 this.$refs.name.offsetHeight 擷取不到值(進階版)

通過 vue 中 this.$refs.name.offsetHeight 擷取不到值 中的需求,【固定高度】的内容如果是通過接口擷取,還是使用那種方法是不可行的。由于接口響應時間是長短不一的,也無法設定一個固定的定時器。那我們怎麼辦呢?

通常我們在請求和響應接口前後都會設定一個 loading 狀态,如下:

getInfo() {
  this.showloading = true;
  this.$axios({ method: "get", url: "xxx", data: {} }).then(res => {
    this.showloading = false;
  });
},
           

當接口響應後,我們将 showloading 設定為 false。把 showloading 的傳遞給子元件中。子元件通過判斷 showloading 的值,再去擷取 子元件的高度,即所謂的【固定高度】。

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

這裡我要提到 watch ,通過 watch 監聽屬性的變化,做出邏輯操作,代碼如下:

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

當接口響應使用者端之後,我們在通過 nextTick 擷取子元件的高度。

繼續閱讀