Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Vue, getting image width within a v-for and assigning dynamic class based on the width?

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!