The way you are doing it is fine. But there is another vue specific way via a ref
attribute.
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>
In this case, since you are just getting the value it really doesn't matter whether you use your original getElementById
approach or the vue specific ref
approach. However if you were setting the value on the element then it's much better to use the ref
approach so that vue understands that the value has changed and won't possibly overwrite the value with the original value if it needs to update that node in the DOM.
You can learn more here: https://vuejs.org/v2/api/#vm-refs
Update
A few people had left comments that the above solution didn't work for them. That solution provided the concepts but not full working code as example, so I have augmented my answer with the code below which demonstrates the concepts.
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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…