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.
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.
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" />