N
Nuxt5mo ago
Jon 久世

Computed Property Not Returning offsetHeight

I'm trying to return the new height of an element when it changes within a computed property. I can see the console.log of the new height after the DOM loads in onMounted, but after this if I try to rescale my browser window it never computes again. All the while I can inspect the element and see that the height has changed. What am I missing here?
const background_video = ref(null)

onMounted(() => {
if (background_video.value) {
console.log('background_video.value.offsetHeight: ', background_video.value.offsetHeight)
}
})

const overlay_height = computed(() => {
console.log('overlay_height: ', background_video.value?.offsetHeight - 128)
return background_video.value?.offsetHeight - 128
})
const background_video = ref(null)

onMounted(() => {
if (background_video.value) {
console.log('background_video.value.offsetHeight: ', background_video.value.offsetHeight)
}
})

const overlay_height = computed(() => {
console.log('overlay_height: ', background_video.value?.offsetHeight - 128)
return background_video.value?.offsetHeight - 128
})
2 Replies
CaptainThreepwood
OffsetHeight is not reactive so the computed property will not update when the element size changes. You can use a resize observer to track the changes and update a ref value. When you use that ref value within the computed calculation it would update the computed property. https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver Or you can use https://vueuse.org/core/useElementSize/ which does it for you
MDN Web Docs
ResizeObserver - Web APIs | MDN
The ResizeObserver interface reports changes to the dimensions of an Element's content or border box, or the bounding box of an SVGElement.
VueUse
Collection of essential Vue Composition Utilities
Jon 久世
Jon 久世4mo ago
Thanks sooo much!! I was about to try setting up an event listener for Window resize, then query the element's offsetHeight. The useElementSize certainly seems much more efficient and less code 💪😃
Want results from more Discord servers?
Add your server