Trying to find the height of a div in Vue.js, I'm accessing it through refs gives error

Viewed 2048

I am trying to find the height of div in Vuejs,

let height = this.$refs.infoBox.clientHeight()+'px';

it gives me an error saying that I cannot find the client height of null / undefined.

2 Answers

If your div have a reference attach to it like: <div ref="infoBox" /> you can access the height of that div with this.$refs.infoBox.offsetHeight.

NOTE: You can access the height of the div only after the component has been mounted. This won't work:

{
  // ...

  created() {
    // WARNING
    // Will trigger an error because the DOM is not mounted at this point.
    console.log(this.$refs.infoBox.offsetHeight);
  },

  // ...
}

Adding onto @geauser's example, if you would like to access a reference after the component is mounted use the mounted hook:

{
  // ...

  mounted() {
    // DOM *is* mounted at this point.
    console.log(this.$refs.infoBox.offsetHeight);
  },

  // ...
}

Vue lifecycle hooks.

Related