Skip to content
Advertisement

Vue js – Set alt image when image source not found

I am working on a site which has a list of products. Each product has a corresponding image. I am binding the image url to the source attribute like below.

<img :src="product.ImageUrl"/>

If the image is not found, I want to show a default image.

I do as below in cshtml razor syntax (for reference only)

onerror='this.onerror = null;this.src = "@Url.Content("~/images/photo-not-available.jpg")";'

How do I achieve the same in Vue?

Advertisement

Answer

You can set an onerror handler function with @error in Vue:

<img :src="" @error="aVueFunctionThatChangesTheSrc">
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement