问题描述
-
在vue3的onMounted中获取到的元素高度与实际高度不符
-
通过nextTick也获取不到实际高度。
以上数据可以通过打印ref实例和ref.value.offersetHeight查看
<div class="video-player" @click="playPauseVideo" ref="playerDiv">
<video style="width: 100%;height:100%;object-fit: fill" ref="player"></video>
</div>
export default {
setup(){
const playerDiv = ref(null);
const playerDivHeight = ref(0);
const player = ref(null);
const playerHeight = ref(0);
onMounted(()=>{
nextTick(()=>{
playerDivHeight.value = playerDiv.value.offsetHeight;
playerHeight.value = player.value.offsetHeight;
//查看打印实例中的value里的offsetHeight属性发现值为772
console.log("playerDiv",playerDiv)
//查看打印的获取值为158
console.log("playerDivHeight", playerDivHeight.value)
//查看打印实例中的value里的offsetHeight属性发现值为764
console.log("player",player)
//查看打印的获取值为150
console.log("playerHeight", playerHeight.value)
})
})
}
}
原因
页面元素和页面资源未完全渲染与加载完,就获取高度,导致获取不准确。
解决方案(参考)
设个定时器,在页面挂载完1秒后再获取高度,就获取到实际高度了,但是有一点,页面体验感不是很好,而且偶尔也会出现获取值不准确现象。如果你有更好的解决方案,可以在下方评论区留言。
export default {
setup(){
const playerDiv = ref(null);
const playerDivHeight = ref(0);
const player = ref(null);
const playerHeight = ref(0);
onMounted(()=>{
let timer = null;
nextTick(()=>{
timer = setInterval(function () {
if (document.readyState === "complete") {
playerDivHeight.value = playerDiv.value.offsetHeight;
playerHeight.value = player.value.offsetHeight;
console.log("playerDiv",playerDiv)
console.log("playerDivHeight", playerDivHeight.value)
console.log("player",player)
console.log("playerHeight", playerHeight.value)
window.clearInterval(timer);
}
}, 1000);
})
})
}
}