Image Binding Error Handling in Vue.js
Zahid Jabbar
Posted on February 19, 2020
π We all know that broken images don't look good and they give a very bad user experience.
π I was working on a project and instead of showing an alt text if the image is broken, I wanted to show some other alternate image. For this, first, I needed to check if the image is broken then show the alternate image.
π I looked for solutions and some people were doing it by styling broken images which is also good but this was not the solution I was looking for.
π I came to know about @error event on images and this proved really helpful.
π¨βπ» Let's explore this with a code example:
π without @error
If we don't use @error
and just provide the alt text, it looks ugly.
<template>
<img class="image" :src="source" alt="mountains" >
</template>
π with @error
By using the @error
event on images, we can show the alternate image if the original image is broken or not loaded for any reason. @error
will only call the provided method if there is any error in loading the original image.
<template>
<img class="image" :src="source" @error="setAltImg" alt="mountains" >
</template>
imgUrlAlt
is the method that sets the image's src to alternate image.
setAltImg(event) {
event.target.src = "working-image.jpg"
}
π― Conclusion
I really liked achieving the same thing in 3-5 lines with @error
and avoiding writing extra 10-15 lines of CSS.
π Say Hi
I am quite active on Twitter you can follow me there or visit my Blog to know more about me.
Posted on February 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 11, 2024