Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

vuejs2

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/

like image 982
Franck Freiburger Avatar asked Feb 02 '17 08:02

Franck Freiburger


People also ask

How do I get element height in Vue?

To get an element's height with Vue. js, we can assign a ref to the element we want to get the height for. Then we can get the height with the clientHeight property of the element that's been assigned the ref. We assigned the ref with the ref prop set to a name.

What is the purpose of slots in Vue?

With Vue slots, you can turn a part or all of your components into reusable templates that will render differently based on different use cases. All you need to do is embed them in slots. In this article, I'll help you understand the concept of Vue slots and show you how to use them.

What is the difference between slots and scoped slots in VUE JS?

In the slot, the component is compiled in the parent's scope and then passed to the child component. So, it is not possible to use child component properties in a slot's content. In Scoped slot, you can pass child component data to the parent scope and then use it in slot content.

What is V cloak in VUE JS?

The v-cloak directive is a Vue. js directive that will remain on the element until the associated Vue instance finishes compilation. Combined with CSS rules such as [v-cloak] { display: none }, this directive can be used to hide uncompiled mustache bindings until the Vue instance is ready.


1 Answers

Use nextTick

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

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

like image 83
CodinCat Avatar answered Oct 16 '22 05:10

CodinCat