onLoad()时,获取某个Dom元素的宽高,但是出现了报错:TypeError: Cannot read property '$el' of undefined
HTML
<view class="JWL_Video_Item_3" ref="viewref">
<view id="JWLvideo-container"></view>
</view>
出错: JavaScript
onLoad(option) {
this.getVideo();
},
methods: {
getVideo() {
let width = this.$refs.viewref.$el.offsetWidth;
let height = this.$refs.viewref.$el.offsetHeight;
}
}
解决: JavaScript
onLoad(option) {
setTimeout(() => { // 设置setTimeout延迟调用
this.getVideo();
}, 1000)
},
methods: {
getVideo() {
let width = this.$refs.viewref.$el.offsetWidth;
let height = this.$refs.viewref.$el.offsetHeight;
}
}
原因
在
onLoad()阶段Dom还没有挂载完成,通过$refs调用Dom就会提示 undefined,可以通过添加延时的方法,等待Dom挂载完成。
本文介绍了在onLoad()函数中尝试访问未完全加载的DOM元素导致TypeError的问题,并提供了解决方案:通过设置setTimeout延迟执行获取DOM元素宽高的操作。
1434

被折叠的 条评论
为什么被折叠?



