在 vue.js 2 中,在渲染插槽后测量组件的高度 [英] In vue.js 2, measure the height of a component once slots are rendered

查看:40
本文介绍了在 vue.js 2 中,在渲染插槽后测量组件的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来读取组件的插槽(在 DOM 中)渲染后的高度 (clientHeight),然后将结果设置为反应数据以进行进一步计算.

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.

根据updated钩子的文档:

调用此钩子时,组件的 DOM 将被更新,因此您可以在此处执行依赖于 DOM 的操作

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

... 似乎不禁止在 updated 钩子中设置反应数据.

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

结果很不稳定,有时在slots渲染后得到clientHeight,有时在渲染前得到.

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.

测试:https://jsfiddle.net/4wv9f052/5/

推荐答案

使用 nextTick

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

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

这篇关于在 vue.js 2 中,在渲染插槽后测量组件的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆