Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 521
Vishwas Avatar asked Feb 28 '18 20:02

Vishwas


2 Answers

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

<img :src="" @error="aVueFunctionThatChangesTheSrc">
like image 193
ceejayoz Avatar answered Dec 28 '22 23:12

ceejayoz


Since in pure js put onerror inline like this

<img :src="ImgUrl" onerror="this.src='http://example.com/default.jpg'"/> 

for vue.js we can replace it

<img :src="ImgUrl" @error="$event.target.src='http://example.com/default.jpg'"/> 

like image 29
Mohsen Avatar answered Dec 29 '22 00:12

Mohsen