How to get component element offset in Vue.js?

I create a component using Vue.js and paste it into the DOM without problems. Once the element is in the DOM, I would like to know its rendering height - i.e. I would like to get its offsetHeight. I cannot figure out how to do this - I have to miss something really obvious. This is what I tried:

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' }); 

But that will not work - "myheight" ends up empty. I thought that maybe the problem was that maybe she was trying to generate the computed property before it was inserted into the DOM, so instead of using the computed property, I tried this:

 Vue.component('my-component',{ template: '#my-component', data: function(){ return { myheight: 999 }; }, ready: function(){ this.myheight = this.offsetHeight; } }); 

Again, it does not work - it does not display anything - and I do not receive any errors or warnings in the console.

Then I thought that this might not have been an HTMLElement, so I searched the Vue documentation and found that all Vue instances should have a $el property that points to an HTMLElement element, or at least how I understood it. .. Therefore, I tried to use this.$el.offsetHeight in both examples above, but again without success.

Can someone point me in the right direction? All help is appreciated ...

+6
source share
1 answer

It seems the problem is with your template. You seem to have a fragment of the instance , which means that you don't have a top-level element that surrounds all children.

So instead, where $el is most likely not going to reference what you want ...

 <!-- component template --> <template id="my-component"> <h1>Hello World</h1> <p>Lorem ipsum dolor sit amet.</h1> <pre>{{ myheight }}</pre> </template> 

... you can wrap your component in a parent element:

 <!-- 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> 

Then you can get the offset height with 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' }); 
+5
source

All Articles