Categories
Vue Answers

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:

<template>
  <div ref="elementToWatch" style="border: 1px solid black; overflow: hidden;">
    <!-- Content that may affect the height of the element -->
  </div>
</template>

<script>
export default {
  mounted() {
    this.$nextTick(() => {
      // Watch the height of the element
      this.watchElementHeight();
    });
  },
  methods: {
    watchElementHeight() {
      const element = this.$refs.elementToWatch;
      
      // Create a new MutationObserver to watch for changes in the height of the element
      const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          // Trigger some action when the height of the element changes
          console.log('Element height changed:', element.clientHeight);
        });
      });
      
      // Configure the MutationObserver to observe changes in the attributes and childList of the target node
      const config = { attributes: true, childList: true, subtree: true };
      
      // Start observing the target node for configured mutations
      observer.observe(element, config);
    }
  }
};
</script>

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *