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挂载完成。