在uni-app x 自定义组件的 mounted 函数执行时,通过 refs 获取元素,再通过getBoundingClientRect获取长宽,得到是的 NAN,是因为此时元素还没渲染吗? 那组件初次渲染完成有对应的生命周期或者其他代替方案吗?

- 发布:2024-01-03 09:29
- 更新:2024-01-03 14:34
- 阅读:405



爱豆豆 - 办法总比困难多
可以用onReady 和 uni.getElementById 来获取长宽
参考下面的代码片段
DOM参考文档:https://doc.dcloud.net.cn/uni-app-x/dom/#getdomnode
<template>
<view>
<view id="viewId">
<text>11111</text>
</view>
</view>
</template>
<script lang="uts">
export default {
onReady() {
const viewDom = uni.getElementById('viewId') as Element
console.log(viewDom.offsetHeight)
console.log(viewDom.offsetWidth)
}
}
</script>

提供以下方案任选其一:
- 使用 uni.createSelectorQuery() 获取
- 使用 onReady 生命周期 (仅页面)
-
h***@geely.com (作者)
感谢!不过onReady 不是页面的生命周期吗? 我在组件里面使用并没有执行。uni.createSelectorQuery() 可行!
2024-01-03 14:23
-
爱豆豆
2024-01-03 11:31