21

It's exactly same as Angular 2 - Check if image url is valid or broken.

how can I implement this in vuejs?

Community
  • 1
  • 1
boombamboo
  • 459
  • 2
  • 5
  • 14
  • The same way: onerror event. – dfsq May 01 '17 at 09:12
  • Possible duplicate of [Detect when an image fails to load in Javascript](http://stackoverflow.com/questions/9815762/detect-when-an-image-fails-to-load-in-javascript) –  May 01 '17 at 20:54

3 Answers3

45

Vue.js has an @error event that you can hook into. From vuejs issue#3261. So you could do:

<template>
   <img :src="avatarUrl" @error="imageLoadError" />
</template>

<script>
export default {
  methods: {
    imageLoadError () {
      console.log('Image failed to load');
    }
  }
};
</script>

Edit: I've discovered this also works for <audio> tags (and I suspect other elements which define a src attribute and load an asset)!

Edit2: Silly me! It's actually an interface for adding a listener to the native onerror event that many HTML elements emit, similar to <input @blur="someHandler">, etc.

kano
  • 5,626
  • 3
  • 33
  • 48
  • I couldn't find any detailed information about `@error` in the documentations of Vue – Asqan Jun 07 '18 at 00:39
  • 1
    @Asqan `onerror` is a valid HTML event that the `` element can emit, so `@error` (or `v-on:error`) is just Vue's syntatic sugar to handle that `onerror` event. It's the same as calling ` – kano Jul 06 '20 at 09:55
23

It seems that @error works fine. I personally used a method with an event in order to set an alternative image.

<img :src="imageUrl" @error="imageUrlAlt">

The method:

imageUrlAlt(event) {
    event.target.src = "alt-image.jpg"
}

From Vue.js issue#5404.

Optimal solution:

<img :src="imageUrl" @error="imageUrl='alt-image.jpg'">

Thanks everyone for your valuable comments.

Jakub A Suplicki
  • 4,586
  • 1
  • 23
  • 31
  • 4
    I quite like this answer. It can be made completely inline without much mess, too. `Company logo` – Matthew Spencer Jul 24 '19 at 10:15
  • 3
    The more Vue approach would be to set a new value for `image` in the `imageUrlAlt` handler: `this.image = 'alt-image.jpg'`, having Vue update the DOM instead of us manually touching it. – kano Jan 19 '20 at 19:13
1

I use a computed property that returns a string with the placeholder URL instead of @error handler like this. This way if source is null or undefined the placeholder will be loaded.

<img :src="source || computedPropertyString" />
  • 6
    This won't work for cases where the `source` is defined but the image doesn't exist on that url (404) or is inaccessible (403). – Mandeep Singh Feb 15 '21 at 21:13