uni-app uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) rect的取值问题
uni-app uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) rect的取值问题
项目属性 | 值 |
---|---|
产品分类 | uniapp/App |
PC开发环境操作系统 | Windows |
PC开发环境操作系统版本号 | win11 |
HBuilderX类型 | 正式 |
HBuilderX版本号 | 4.61 |
手机系统 | Android |
手机系统版本号 | Android 15 |
手机厂商 | OPPO |
手机机型 | 真我GT6 |
页面类型 | vue |
vue版本 | vue3 |
打包方式 | 离线 |
项目创建方式 | HBuilderX |
操作步骤:
代码const instance = getCurrentInstance();
uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) => {
console.log(rect)
})
.exec();
预期结果:
应该打印出view的高度值
实际结果:
编译报错20:58:21.021 开始差量编译...
20:58:23.332 [plugin:uni:app-uts] 编译失败
20:58:23.332 error: Unresolved reference: height
20:58:23.332 at components/fold/fold.uvue:69:20
20:58:23.332 67 | const instance = getCurrentInstance();
20:58:23.332 68 | uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) => {
20:58:23.332 69 | console.log(rect.height)
20:58:23.332 | ^
20:58:23.332 70 | })
20:58:23.332 71 | .exec();
bug描述:
const instance = getCurrentInstance();
uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) => {
console.log(rect.height)
})
.exec();
这段代码使用浏览器运行没有问题,但是运行到安卓(无论是真机还是模拟器)都会报错20:43:53.326 [plugin:uni:app-uts] 编译失败
20:43:53.326 error: Unresolved reference: height
20:43:53.326 at components/fold/fold.uvue:69:20
20:43:53.328 67 | const instance = getCurrentInstance();
20:43:53.328 68 | uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) => {
20:43:53.328 69 | console.log(rect.height)
20:43:53.328 | ^
20:43:53.328 70 | })
20:43:53.328 71 | .exec();
但是如果是console.log(rect)的话可以打印出
20:56:42.688 [io.dcloud.uniapp.framework.extapi.NodeInfo] {bottom: 340.28570556640625, context: null, dataset: null, height: 306.28570556640625, id: null, ...} at components/fold/fold.uvue:69
试过各种办法均无法取出rect的字段参数
更多关于uni-app uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) rect的取值问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
4 回复
rect 是 any 类型 需要先as类型后. (rect[0] as NodeInfo).height
参考文档 https://doc.dcloud.net.cn/uni-app-x/api/create-selector-query.html
更多关于uni-app uni.createSelectorQuery().in(instance).select(".data").boundingClientRect((rect) rect的取值问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
感谢!解决了
楼主方便贴个解决后的完整代码给我看看吧,
这个问题的原因是UTS编译环境下对rect对象的类型检查更严格。在浏览器运行时可以正常访问rect.height,但在UTS编译时需要明确rect的类型定义。
解决方案是使用类型断言或通过索引方式访问:
- 使用类型断言:
boundingClientRect((rect: any) => {
console.log(rect.height)
})
- 通过索引方式访问:
boundingClientRect((rect) => {
console.log(rect['height'])
})
- 或者定义完整类型:
interface Rect {
height: number
width: number
// 其他属性...
}
boundingClientRect((rect: Rect) => {
console.log(rect.height)
})