在 vue.js 2 中,在渲染插槽后测量组件的高度

编程入门 行业动态 更新时间:2024-10-11 09:23:56
本文介绍了在 vue.js 2 中,在渲染插槽后测量组件的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在寻找一种方法来读取组件的插槽(在 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/4wv9f052/5/

推荐答案

使用 nextTick

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

https://jsfiddle/4wv9f052/9/

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

更多推荐

[db:关键词]

本文发布于:2023-04-27 01:58:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1146359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:插槽   组件   测量   高度   vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!