Reinier68
Reinier68

Reputation: 3324

How to keep track of the height of a component in Vuejs?

I need to keep track of the height of a component from the moment it gets rendered to the DOM. I've tried a bunch of things but unfortunately to no prevail. I created a codesandbox to better illustrate my problem.

I defined a property oneCol in my data object that looks like this:

oneCol: [
  {
    id: 0,
    component: KeepTrackOfHeight,
    height: undefined /*keep track of height here, but how?*/
  }
],

I then render that component with a simple v-for loop with the following code:

<div v-for="(component, idx) in oneCol" :key="idx">
  <component :is="component.component" :text="text"/>
</div>

Now I would like to keep track of the height of the component, so that from the moment it renders, the height in my oneCol property gets set to the height of the component. Also, when text gets added to the component, the height will obviously change. That change also has got to be reflected in the oneCol property.

I have not been able to set the initial width of the component in the oneCol property, let alone keeping track of height changes. I've tried setting a ref on the component and setting the height in the mounted hook:

mounted(){
    this.entries.forEach((entry, idx) => {
        this.oneCol.push({ idx: idx, component: KeepTrackOfHeight, height: this.$refs.componentName.$el.clientHeight})
    })
}

However, height will be undefined because the element will not be created yet.

Any help, info, ideas on how I can improve and keep track of the height would be greatly appreciated.

Upvotes: 0

Views: 1284

Answers (1)

Thomas Kuhlmann
Thomas Kuhlmann

Reputation: 1003

I am not sure why you are trying to capture the height, there might be better approaches (e.g. CSS-only)... But if you use this:

mounted(){
this.$nextTick().then(()=> {
    this.entries.forEach((entry, idx) => {
        this.oneCol.push({ idx: idx, component: KeepTrackOfHeight, height: this.$refs.componentName.$el.clientHeight})
        })
    }
}

your DOM has finished rendering and $refs are available

Vue.nextTick

Upvotes: 2

Related Questions