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?
2 Replies
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
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 💪😃