How to watch height of an element in Vue.js?

Spread the love

To watch the height of an element in Vue.js, we can use a combination of a ref and a watcher.


For instance we write:

In this example we use a ref (elementToWatch) to access the element whose height we want to watch. We use mounted lifecycle hook to ensure that the element is available in the DOM before we attempt to watch its height. Inside the watchElementHeight method, we create a new MutationObserver to observe mutations on the target element.
We configure the MutationObserver to observe changes in attributes, child nodes, and subtree of the target node.
We define a callback function that will be executed whenever a mutation is observed. In this callback, we can perform actions based on changes in the height of the element.
Finally, we call observe on the MutationObserver instance to start observing the target node for mutations.
This setup allows we to watch for changes in the height of the target element and trigger actions accordingly.
Adjust the actions inside the MutationObserver callback as needed based on our specific requirements.