你正在做它的方式是好的。但是通過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>
這裏是在瀏覽器中結果的截圖:
https://stackoverflow.com/a/526352/2316112 –
你能創建一個再生產?它似乎工作得很好:https://jsfiddle.net/wostex/63t082p2/84/(如果你從你的方法當然返回高度,因爲在你的代碼中你什麼都不返回)。 – wostex
其實我的組件有很多線條和方法。我在這裏簡化了它。但我不明白爲什麼它返回的數字小於實際高度(檢查元素時)。這是一個加載問題嗎? 不應該加載時運行該方法嗎? –