It's exactly same as Angular 2 - Check if image url is valid or broken.
how can I implement this in vuejs?
To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.
A 'description' data variable is also created which holds the Heading of the Page i.e “How to check if an image is loaded in VueJs?”. Assign a '@load' event to the Image. The name of the event will be 'loadImage', and its function will be to change the value of 'isLoaded' to “True” if the image gets loaded.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With