2017-07-06 362 views
3

我想獲得div的高度,以便使其他div的高度與其匹配。我使用了方法clientHeight,但它不會返回給我的好值(較小的值)。實際上,在所有元素被收費之前,它似乎都會返回一個高度。 經過一些在線研究,我試圖放置一個window.load()來延遲,直到所有東西都被充電,但它不起作用。一些想法?使用Vuejs獲取元素高度

mounted() { 
 
    this.matchHeight() 
 
}, 
 
matchHeight() { 
 
    let height = document.getElementById('info-box').clientHeight 
 
}
<div class="columns"> 
 
    <div class="left-column" id="context"> 
 
    <p>Some text</p> 
 
    </div> 
 
    <div class="right-column" id="info-box"> 
 
    <img /> 
 
    <ul> 
 
     some list 
 
    </ul> 
 
    </div> 
 
</div>

+0

https://stackoverflow.com/a/526352/2316112 –

+3

你能創建一個再生產?它似乎工作得很好:https://jsfiddle.net/wostex/63t082p2/84/(如果你從你的方法當然返回高度,因爲在你的代碼中你什麼都不返回)。 – wostex

+0

其實我的組件有很多線條和方法。我在這裏簡化了它。但我不明白爲什麼它返回的數字小於實際高度(檢查元素時)。這是一個加載問題嗎? 不應該加載時運行該方法嗎? –

回答

7

你正在做它的方式是好的。但是通過ref屬性還有另外一種具體的方法。

mounted() { 
    this.matchHeight() 
}, 
matchHeight() { 
    let height = this.$refs.infoBox.clientHeight; 
} 


<div class="columns"> 
     <div class="left-column" id="context"> 
      <p>Some text</p> 
     </div> 
     <div class="right-column" id="info-box" ref="infoBox"></> 
      <img /> 
      <ul> 
       some list 
      </ul> 
     </div> 
    </div> 

在這種情況下,因爲你是剛剛起步的價值真的不要緊,你是否使用原來的getElementById方法或VUE具體ref方法。但是,如果您在元素上設置值,那麼使用ref方法好得多,這樣vue就會明白該值已更改,並且如果需要更新DOM中的該節點,則不會使用原始值覆蓋該值。

您可以在這裏瞭解更多:https://vuejs.org/v2/api/#vm-refs

更新

有幾個人已經離開評論說,上述方案並沒有爲他們工作。該解決方案提供了概念,但沒有提供完整的工作代碼作爲示例,所以我用下面的代碼展示了我的答案,它演示了這些概念。

var app = new Vue({ 
 
    el: '#app', 
 
    data: function() { 
 
     return { 
 
      leftColStyles: { }, 
 
      lines: ['one', 'two','three'] 
 
     } 
 
    }, 
 
    methods: { 
 
     matchHeight() { 
 
      var heightString = this.$refs.infoBox.clientHeight + 'px'; 
 
      Vue.set(this.leftColStyles, 'height', heightString); 
 
     } 
 
    }, 
 
    mounted() { 
 
     this.matchHeight(); 
 
    } 
 

 
});
.columns{width:300px} 
 
.left-column {float:left; width:200px; border:solid 1px black} 
 
.right-column {float:right; border:solid 1px blue; }
<div id="app"> 
 
    <div class="columns"> 
 
     <div class="left-column" id="context" v-bind:style="leftColStyles"> 
 
      <p>Some text</p> 
 
     </div> 
 
     <div class="right-column" id="info-box" ref="infoBox"> 
 
      <img /> 
 
      <ul> 
 
       <li v-for="line in lines" v-text="line"></li> 
 
      </ul> 
 
     </div> 
 
    </div> 
 

 
</div> 
 

 
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script> 
 

這裏是在瀏覽器中結果的截圖:

enter image description here

+0

謝謝,我試過你的解決方案,但同樣的問題。我注意到包含列表的div沒有被考慮在內。它只會返回圖像的高度。 但列表中有一個v-if =「someVariable」,這似乎是原因,不是? –

+0

什麼問題? –

+0

該列表未被考慮。好像它沒有被顯示,但它是。 –