1、TypeError: Cannot read property 'left' of null
小程序和H5运行正常,但是App运行就报以下错误
19:10:31.860 [Vue warn]: Error in event handler for "view.onRequestComponentInfo": "TypeError: Cannot read property 'left' of null"
19:10:31.908 (found <Root>)
19:10:31.931 TypeError: Cannot read property 'left' of null
错误比较明显,但是会发现,left 这个属性是有的,于是各种定位问题,最终发现问下出现在uni-app的Api调用时机上
又是官方文档的锅,官方文档说:createSelectorQuery 方法,需要在 mounted() 生命周期调用
实际也是这么操作的,但是实际会发现boundingClientRect((res)) 方法中的res会一直返回null,导致或许全都出错
基于之前客户端的开发经验,这里肯定是取值时,还没完全渲染完,于是,加点延迟,问题解决
# 出错代码
mounted() {
setTimeout(() => {
const query = uni.createSelectorQuery().in(this);
query.select('.tab-box').boundingClientRect((res) => {
this.box = res;
this.updateTabWidth();
}).exec();
}, 0);
}
# 正确代码
mounted() {
setTimeout(() => {
const query = uni.createSelectorQuery().in(this);
query.select('.tab-box').boundingClientRect((res) => {
this.box = res;
this.updateTabWidth();
}).exec();
}, 300);
}