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, you can use a combination of Vue’s reactivity system and DOM manipulation.

We can do the following:

Template

Add a reference to the element whose height you want to watch.

<template>
  <div ref="elementToWatch">
    <!-- Your content here -->
  </div>
</template>

Script

Set up a watcher to monitor changes in the height of the element.

<script>
export default {
  data() {
    return {
      elementHeight: 0
    };
  },
  mounted() {
    // Call the method to get the initial height
    this.getElementHeight();
    // Listen for resize events
    window.addEventListener('resize', this.getElementHeight);
  },
  beforeDestroy() {
    // Remove the resize event listener to prevent memory leaks
    window.removeEventListener('resize', this.getElementHeight);
  },
  methods: {
    getElementHeight() {
      // Access the element using the ref and get its height
      const element = this.$refs.elementToWatch;
      if (element) {
        this.elementHeight = element.clientHeight;
      }
    }
  }
};
</script>

Template Usage

Display or use the elementHeight variable wherever you need it in your template.

<template>
  <div>
    The height of the element is: {{ elementHeight }}px
  </div>
</template>

This approach ensures that whenever the height of the element changes (due to window resizing or dynamic content changes), the elementHeight variable is updated accordingly.

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 *