Skip to content
Advertisement

Vuetify dynamic height for v-img

I have a container that is not 100% height of the page, it is 80% plus 60px on top and on bottom. So the image inside should inherit the height of the container.

Using the <img /> and a little of CSS it is easy to achieve but I wish to add a template with loading spinner and so I started using the <v-img> for it.

I can see I can set the height or the max-height and so I did a method to calculate the parent height minus the 120px to get the exact image height, and it is working as expected.

The issue is when the user resize the window, I can see the method to be called and updating the value but the vuetify element is not responsive to the new values and so the image is bigger or smaller than container:

<div id="photoWrapper" class="photo-wrapper">
  <v-img
    :src="photo.url"
    :contain="true"
    :max-height="wrapperHeight()"
  >
    <template v-slot:placeholder>
      <v-layout fill-height align-center justify-center ma-0>
        <v-progress-circular
          indeterminate
          color="tertiary"
        ></v-progress-circular>
      </v-layout>
    </template>
  </v-img>
</div>

Code:

data() {
  return {
    mounted: false
  }
},
mounted() {
  this.mounted = true
  window.addEventListener('resize', this.wrapperHeight)
  this.wrapperHeight()
},
methods: {
  wrapperHeight() {
    if (!this.mounted) return
    console.log(document.getElementById('photoWrapper').offsetHeight - 120)
    const height = document.getElementById('photoWrapper').offsetHeight - 120
    return height
  }
}

The method is always called on screen resize, but the image is not responsive. How can I do it? I also tried to move the wrapperHeight to be a computed property.

Advertisement

Answer

The solution is to do a mix between computed and methods like so:

data() {
  return {
    mounted: false,
    containerHeight:
      document.getElementById('photoWrapper').offsetHeight - 120
  }
},
computed: {
  wrapperHeight() {
    if (!this.mounted) return
    const height = this.containerHeight
    return height
  }
},
mounted() {
  this.mounted = true
  window.addEventListener('resize', _.debounce(this.handleResize, 100))
},
beforeDestroy() {
  window.removeEventListener('resize', this.handleResize)
},
methods: {
  handleResize() {
    this.containerHeight =
      document.getElementById('photoWrapper').offsetHeight - 120
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement