0

I'm trying to obtain width of image within loop and give class based upon width? My attempt was to use a getWidth function that takes the image source, loads it then returns a width. For some reason, the width is always a empty string.

<template>
  <div id="app">
    <div v-for="image in images" :key="image">
      width: {{ getWidth(image) }}
      <img
        :class="getWidth(image) > 450 ? 'large' : 'small'"
        :alt="image"
        :src="image"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      images: [
        'http://placeimg.com/640/480/business',
        'https://vuejs.org/images/logo.png',
      ],
    };
  },
  methods: {
    getWidth(src) {
      let width;
      const image = new Image();
      image.src = src;
      image.onload = function () {
        width = this.width;
        console.log(this.width);
      };
      return width;
    },
  },
};
</script>

Why would this not work?? https://stackblitz.com/edit/vue3-app-bk8sef

Mike Shiv
  • 203
  • 4
  • 12
  • See https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call . You can't return width inside getWidth and shouldn't call it in a template at all. If `images` is available on component mount then you need to do all asynchronous side effects there – Estus Flask Feb 13 '22 at 16:48
  • Oh so I should handle it all within a mounted hook? Got it – Mike Shiv Feb 13 '22 at 17:02

0 Answers0