7

I need to get the height of an image/element, this is what I did:

mounted() {
   this.infoHeight = this.$refs.info.clientHeight + 'px';
}

When I save then on hot reload it works, it gets the correct height but when I refresh the page it returns a smaller/wrong value. I also tried it on created() and it's the same. On other situations it doesn't even return anything.

UPDATE (Temporary solution?)

mounted() {
       setTimeout(() => this.infoHeight = this.$refs.info.clientHeight + 'px', 100);
}

I also tried using window.addEventListener('load', () => //todo) but on some components it worked and on others it didn't.

2
  • 1
    Thanks for the update. I'm running into the exact same issue and using setTimeout in mounted fixed it for me too, now I get consistent heights when hot reloading and refreshing.
    – Tobberoth
    Feb 18, 2020 at 13:29
  • Thanks for the workaround, this is working while nextTick don't
    – Jona
    Feb 17, 2021 at 16:01

3 Answers 3

4

You can do this now in a way cleaner fashion using a ResizeObserver.

  data: () => ({
    infoHeight: 0,
    resizeObserver: null
  }),
  mounted() {
    this.resizeObserver = new ResizeObserver(this.onResize)
    this.resizeObserver.observe(this.$refs.info)
    this.onResize()
  },
  beforeUnmount() {
    this.resizeObserver.unobserve(this.$refs.info)
  },
  methods: {
    onResize() {
      this.infoHeight = this.$refs.info.clientHeight + 'px'
    }
  }
2
  • 1
    This one actually worked for me. Using addEventListener on the window worked on resize but not on the initial load. This should ideally be the top answer.
    – Manpreet
    Sep 16, 2022 at 10:08
  • Stumbled upon this thread and this answer after along search and have to say, that the ResizeObserver helped me as well! In my case, I am watching this.$root.$el which has a height 0 after the first mount as well.
    – dopenguin
    Jan 4 at 17:37
3

Try with $nextTick which will execute after DOM update.

mounted() {
   this.$nextTick(() => { this.infoHeight = this.$refs.info.clientHeight + 'px' });
}
3
  • same problem, on hot reload it works but as soon as I refresh I get the wrong height. Jan 1, 2020 at 8:46
  • @KevinBryan : try with computed property then Jan 1, 2020 at 10:23
  • Same problem. Very weird that such a popular framework like Vue.js have this kind of bug.
    – Ballon Ura
    Oct 31, 2020 at 10:19
1

You could use this.$watch with immediate:true option :

  mounted () {
    this.$watch(
        () => {
            return this.$refs.info
        },
      (val) => {
        this.infoHeight = this.$refs.info.clientHeight + 'px'
      },
      {
        immediate:true,
        deep:true
       }
    )
  }

The above solution works only in the initial mount, the following one use MutationObserver

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: () => ({
    infoHeight: 0,
    observer: null,

    img: "https://images.ctfassets.net/hrltx12pl8hq/6TOyJZTDnuutGpSMYcFlfZ/4dfab047c1d94bbefb0f9325c54e08a2/01-nature_668593321.jpg?fit=fill&w=480&h=270"

  }),
  mounted() {
    const config = {
      attributes: true,
      childList: true,
      subtree: true
    };
    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation) {
          this.infoHeight = this.$refs.info.clientHeight + 'px'
          console.log(" changed ", this.$refs.info.clientHeight)
        }
      });
    });
    this.observer.observe(this.$refs.info, config);


  },

  methods: {
    changeImg() {
      this.img = "https://i.pinimg.com/originals/a7/3d/6e/a73d6e4ac85c6a822841e449b24c78e1.jpg"
    },

  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  <p>{{infoHeight}}</p>

  <button class="btn btn-primary" @click="changeImg">Change image</button>
  <div ref="info">
    <img :src="img" alt="image" />
  </div>
</div>

2
  • This isn't going to work because the clientHeight is not a reactive property and a change won't be noticed by Vue. Jul 10, 2021 at 20:52
  • thank you for your comment I'll try to find a working solution and I'll let you know Jul 10, 2021 at 21:02

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.