Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs - Check if image url is valid or broken

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

how can I implement this in vuejs?

like image 308
boombamboo Avatar asked May 01 '17 05:05

boombamboo


People also ask

How do you check if a URL is a valid image?

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.

How do I know if an image is loaded or not in Vue?

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.


2 Answers

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.

like image 132
kano Avatar answered Oct 12 '22 00:10

kano


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.

like image 38
Jakub A Suplicki Avatar answered Oct 12 '22 01:10

Jakub A Suplicki