Stephan-v
Stephan-v

Reputation: 20299

Vue element height under a tab

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?

Upvotes: 1

Views: 778

Answers (1)

Florian Haider
Florian Haider

Reputation: 1912

Vue uses an async update queue for doing DOM changes (see https://v2.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
})

Upvotes: 1

Related Questions