How to check if image URL is valid or broken with Vue.js?

Sometimes, we want to check if image URL is valid or broken with Vue.js.

In this article, we’ll look at how to check if image URL is valid or broken with Vue.js.

How to check if image URL is valid or broken with Vue.js?

To check if image URL is valid or broken with Vue.js, we can handle the error event triggered by the img element.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div>
    	<img src='abc' @error='onError'>
    </div>
  `,
  methods: {
    onError() {
      console.log('img failed to load')
    }
  }
})

to add an img element into the template.

And we set @error to onError to run onError when the image fails to load.

Since the img element’s src attribute isn’t a valid URL, onError will run.

Conclusion

To check if image URL is valid or broken with Vue.js, we can handle the error event triggered by the img element.