It's exactly same as Angular 2 - Check if image url is valid or broken.
how can I implement this in vuejs?
It's exactly same as Angular 2 - Check if image url is valid or broken.
how can I implement this in vuejs?
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.
@error in the documentations of Vueonerror 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/…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.
<img :src="viewModel.logo" @error="$event.target.src = '[source image]'" alt="Company logo" />image in the imageUrlAlt handler: this.image = 'alt-image.jpg', having Vue update the DOM instead of us manually touching it.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" />
source is defined but the image doesn't exist on that url (404) or is inaccessible (403).