1

I want to give the same height to a div containing Component2 as another div (modelDiv) containing Component1.

<template>
  <div>
    <div v-if="showMe">
      <div ref="modelDiv">
        <Component1/>
      </div>
    </div>
    <div v-else>
      <div :style="setDivHeight">
        <Component2/>
      </div>
    </div>
  </div>
</template>

<script>

export default {

  data() {
    return {
      displayMe: true,
      elementHeight: null,
    }
  },
  computed: {
    showMe() {
      return this.displayMe
    },
    setDivHeight() {
      return `height: ${this.elementHeight}px;`
    },
  },

  mounted() {
    this.$nextTick(function () {
      this.elementHeight = this.$refs.modelDiv[0].$el.clientHeight
    })
  },
}
</script>

I am having this error message TypeError: Cannot read properties of undefined (reading '$el') and console.log('the height', this.$refs) gives me modelDiv: undefined. I can't figure out why. Any help is welcome.

kissu
  • 40,416
  • 14
  • 65
  • 133
Maxime
  • 337
  • 2
  • 17
  • Another problem besides modelDiv[0] is https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback . Don't use `function` for callbacks unless you know it won't cause problems. Also nextTick not needed here, the ref is supposed to be available in mounted – Estus Flask Nov 05 '21 at 06:26
  • Try inspecting the element in your Vue devtools, click on the element and look for `$vm0` in your console. Or you can also `console.log(this.$refs.modelDiv)` and see what you get from here. – kissu Nov 05 '21 at 10:35

2 Answers2

1

That should work:

this.elementHeight = this.$refs.modelDiv.clientHeight;

Demo: https://codesandbox.io/s/ref-kloqu?file=/src/App.vue

Cianekjr
  • 366
  • 1
  • 4
0

Since I see only see one div with ref as modelDiv, jus try using one of the below options amd see if that works

this.elementHeight = this.$refs.modelDiv.$el.clientHeight

Or

this.elementHeight = this.$refs.modelDiv.clientHeight
Amaarockz
  • 4,348
  • 2
  • 9
  • 27