0

I have a table with multiple rows and a <td> loading a dynamic url image using Vuetify

<v-data-table :headers="headers" :items="items">
  <template slot="items" scope="props">
      <td>
         <img :src="getImgUrl(props.item.styleCode)" />
      </td>
  </template>
</v-data-table>

and then

checkImage(imageSrc, good, bad) {
   let img = new Image();
   img.onload = good;
   img.onerror = bad;
   img.src = imageSrc;
},
getImgUrl(styleCode) {
  var image = 'http://192.168.1.19/Images/ClassImages/' + styleCode + '.png';

  this.checkImage(image,
  function () {
     return 'http://192.168.1.19/Images/ClassImages/' + styleCode + '.png';
  }, function () {
     return 'http://192.168.1.19/Images/ClassImages/default.png';
  });
}

This return nothing. What are I doing bad?

Edit: This is to load an external image and if doesn't exist load a default image

2
  • 2
    You're not returning anything in either method Commented Aug 29, 2017 at 17:32
  • It's a callback that work properly if I write console.log('good') of console.log('bad') in the getImgUrl function Commented Aug 29, 2017 at 17:34

1 Answer 1

5

You're not returning anything in the getImgUrl method, meaning you're not binding the src attribute to anything.

It'd be much simpler to attempt to set the src and then use an @error listener directly on the img element to handler the event of a failed load:

new Vue({
  el: '#app',
  methods: {
    getImgUrl(i) {
      if (i === 4) {
      	return 'http://thisonewontwork';
      }
      return 'http://placehold.it/120x120&text=image' + i;
    },
    onError(e) {
      let defaultURL = 'http://placehold.it/120x120&text=default';
      if (e.target.src !== defaultURL) {
        e.target.src = defaultURL;
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <template v-for="i in 4">
    <img :src="getImgUrl(i)" @error="onError">  
  </template>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

I was using this <img :src="getImgUrl(props.item.styleCode)" onerror="this.onerror = null; this.src = '192.168.1.19/Images/ClassImages/no_image_mdpi.png';"> but I think your solution is cleaner. Thanks
I was trying avoid the 404 not found in the console with my approach...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.