[英]How Do I Get The offsetHeight of a Component Element in Vue.js?
我正在使用Vue.js創建一個組件,並將其插入到DOM中而沒有任何問題。 一旦元素在DOM中,我想知道它的渲染高度 - 也就是說,我想得到它的offsetHeight 。 我無法解決如何做到這一點 - 我必須遺漏一些非常明顯的東西。 這就是我嘗試過的:
HTML:
<!-- vue instance -->
<div id="my-app">
<my-component></my-component>
</div>
<!-- component template -->
<template id="my-component">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet.</h1>
<pre>{{ myheight }}</pre>
</template>
Vue Javascript:
Vue.component('my-component',{
template: '#my-component',
computed: {
myheight: function(){
return this.offsetHeight;
}
}
});
Vue({ el: '#my-app' });
但它不起作用 - 'myheight'最終為空。 我認為可能問題是它可能在插入到DOM之前嘗試生成計算屬性,因此我嘗試使用計算屬性而不是:
Vue.component('my-component',{
template: '#my-component',
data: function(){
return {
myheight: 999
};
},
ready: function(){
this.myheight = this.offsetHeight;
}
});
同樣,它不起作用 - 它什么都不輸出 - 我在控制台中沒有收到任何錯誤或警告。
然后,我想也許this
不是一個HTMLElement,所以我搜索了Vue文檔,發現所有Vue實例都應該有一個指向HTMLElement的$el
屬性 - 或者至少是我理解它的方式......所以我在上面的兩個例子中都試過使用this.$el.offsetHeight
,但是再次沒有成功。
有人能指出我正確的方向嗎? 所有的幫助表示贊賞......
看起來問題出在您的模板中。 您似乎有一個片段實例 ,這意味着您沒有包圍所有子項的頂級元素。
所以,而不是這個, $el
很可能沒有提到你想要的東西......
<!-- component template -->
<template id="my-component">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet.</h1>
<pre>{{ myheight }}</pre>
</template>
...你可以將你的組件包裝在父元素中:
<!-- component template -->
<template id="my-component">
<div class="my-component">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet.</p> <!-- and close the tag correctly -->
<pre>{{ myheight }}</pre>
</div>
</template>
然后你可以使用this.$el.offsetHeight
獲得偏移高度this.$el.offsetHeight
:
Vue.component('my-component',{
template: '#my-component',
data: function(){
return {
myheight: 999
};
},
ready: function(){
this.myheight = this.$el.offsetHeight;
}
});
new Vue({ el: '#my-component' });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.