Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda