Franck Freiburger
Franck Freiburger

Reputation: 28448

In vue.js 2, measure the height of a component once slots are rendered

I am looking for a way to read the height (clientHeight) of a component after its slots are rendered (in the DOM) and then set the result to a reactive data for further computations.

According to the documentation of the updated hook:

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here

... It's ok until then, but the documentation also states:

However, in most cases you should avoid changing state inside the hook

... It seems that this is not prohibited to set reactive data in the updated hook.

The result is very instable, sometimes I get the clientHeight after slots are rendered, and sometimes before they are rendered.

It seems that 'updated' hook is called at the right moment but changing the reactive data in this hook does not work systematically.

test: https://jsfiddle.net/4wv9f052/5/

Upvotes: 6

Views: 3331

Answers (1)

CodinCat
CodinCat

Reputation: 15914

Use nextTick

Vue.nextTick(() => {
  this.height = this.$el.clientHeight;
});

https://jsfiddle.net/4wv9f052/9/

Upvotes: 3

Related Questions