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