27

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

how can I implement this in vuejs?

2
  • The same way: onerror event. Commented May 1, 2017 at 9:12
  • Possible duplicate of Detect when an image fails to load in Javascript Commented May 1, 2017 at 20:54

3 Answers 3

50

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.

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

2 Comments

I couldn't find any detailed information about @error in the documentations of Vue
@Asqan onerror is a valid HTML event that the <img> 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 <button @click="clickHandler">, <input @blur="blurHandler"> or any other event listener for a valid HTML event. developer.mozilla.org/en-US/docs/Web/HTML/Element/…
28

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.

2 Comments

I quite like this answer. It can be made completely inline without much mess, too. <img :src="viewModel.logo" @error="$event.target.src = '[source image]'" alt="Company logo" />
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.
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" />

1 Comment

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).

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.