onReady() {
let queryTabSize = uni.createSelectorQuery().in(this);
queryTabSize.select('#tab-devide-line-id').boundingClientRect();
queryTabSize.exec(rects => {
rects.forEach((rect) => {
console.log(rect);//输出为0
})
});
}
![w***@163.com](https://img-cdn-tc.dcloud.net.cn/account/identicon/df4d107691b18e5c2cd670b303c863cb.png)
- 发布:2022-03-23 09:47
- 更新:2022-03-25 16:29
- 阅读:396
产品分类: uniapp/App
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: win10
HBuilderX类型: 正式
HBuilderX版本号: 3.3.13
手机系统: Android
手机系统版本号: Android 10
手机厂商: 小米
手机机型: 小米8se
页面类型: nvue
vue版本: vue2
打包方式: 云端
项目创建方式: HBuilderX
操作步骤:
预期结果:
输出组件宽度及其他属性值
输出组件宽度及其他属性值
实际结果:
组件宽度及其他属性均为0
组件宽度及其他属性均为0
bug描述:
onReady方法中马上获取组件宽度,结果为0,代码如下:
onReady() {
let queryTabSize = uni.createSelectorQuery().in(this);
queryTabSize.select('#tab-devide-line-id').boundingClientRect();
queryTabSize.exec(rects => {
rects.forEach((rect) => {
console.log(rect);//输出为0
})
});
}
延时一段时间(比如1秒)后,能获取到正确宽度,代码如下:
onReady() {
this.timer = setTimeout( () => {
let queryTabSize = uni.createSelectorQuery().in(this);
queryTabSize.select('#tab-devide-line-id').boundingClientRect();
queryTabSize.exec(rects => {
rects.forEach((rect) => {
console.log(rect);//输出正确宽度
})
});
}, 1000);
}
![w***@163.com](https://img-cdn-tc.dcloud.net.cn/account/identicon/df4d107691b18e5c2cd670b303c863cb.png)
w***@163.com (作者)
不延时执行的话,官方解决方案示例代码获取的值仍然为0,延时一秒执行,获取的值正常。复现代码如下:
<template>
<view class="wrapper">
<view ref="box" class="box">
<text class="info">Width: {{size.width}}</text>
<text class="info">Height: {{size.height}}</text>
<text class="info">Top: {{size.top}}</text>
<text class="info">Bottom: {{size.bottom}}</text>
<text class="info">Left: {{size.left}}</text>
<text class="info">Right: {{size.right}}</text>
</view>
</view>
</template>
<script>
// 注意平台差异
// #ifdef APP-NVUE
const dom = weex.requireModule('dom')
// #endif
export default {
data () {
return {
size: {
width: 0,
height: 0,
top: 0,
bottom: 0,
left: 0,
right: 0
}
}
},
onReady () {
const result = dom.getComponentRect(this.$refs.box, option => {
console.log('getComponentRect:', option)
this.size = option.size
console.log('this.size:', this.size)
})
console.log('return value:', result)
console.log('viewport:', dom.getComponentRect('viewport'))
}
}
</script>
<style>
.box {
width: 200rpx;
height: 500rpx;
left: 100rpx;
top: 100rpx;
}
</style>
w***@163.com (作者)
为什么延时后执行能正确获取到数据呢
2022-03-25 14:16
w***@163.com (作者)
回复 DCloud_UNI_Anne: 但是确实获取到了呢
2022-03-25 14:31