1
votes

I currently have a component that is not initially displayed because it is under a tab. This component get the height of the element that is put inside of the unnamed default slot like so:

this.$el.offsetHeight

This will fail because the element is not displayed therefore I have implemented an event bus and when the tab is clicked I fire an event to let the component know he can read the height.

The problem that I am running into though is that the tab takes a little bit of time to render apparently. When I try to read the offsetHeight straight away it does not work.

However when I throw a setTimeout around the function that reads the height with only 50ms delay it works perfectly fine.

I do not want to rely on an arbitrary like 50ms for this though. Is there some way for Vue to let me know when the content is actually displayed here?

Is it normal for there to be such an delay between the event emitted to the event bus till the event being handled in another component?

1
Try reading offsetHeight in the nextTick callback, then it should work vuejs.org/v2/api/#Vue-nextTickFlorian Haider
I have just tried my example with a setTimeout of 0 and it works. It works with nextTick as well. I guess nextTick kind of works the same by queuing the asynchronous code?Stephan-v
@FlorianHaider Nice! Thanks for your help. Feel free to make a proper answer for me to accept.Stephan-v

1 Answers

1
votes

Vue uses an async update queue for doing DOM changes (see https://vuejs.org/v2/guide/reactivity.html#Async-Update-Queue), so use the Vue.nextTick function for reading offsetHeight:

Vue.nextTick(() => {
    // here the value will be set
    this.$el.offsetHeight
})