Dominik
Dominik

Reputation: 4768

Vue.js/Nuxt.js Load Fallback Image on 404

I am trying to set a default image (placeholder image) in case the image resource is not found (404). I have a dict article which has a value for the key author_image. So that string is not empty but it just can't load that image.

In my template:

<img
 :src="article.author_image"
 alt="Author Image"
 @error="setFallbackImageUrl"
>

In my methods:

methods: {
    setFallbackImageUrl(event) {
        console.log('Image failed to load, setting fallback.')
        event.target.src = '~/assets/icons/avatar.svg'
    }
}

I can see in my console log that setFallbackImageUrl is called but the image src is not updated. I made sure that the avatar.svg is actually correct, if I just hard code that over article.author_image that works.

Any suggestions on what I might be doing wrong?

Upvotes: 2

Views: 2891

Answers (2)

mahatmanich
mahatmanich

Reputation: 11023

Just in case someone is hitting a brick wall with webpack (files from assets/static) The accepted answer from here should resolve it:

Dynamic img src URL with "OR" statement not working properly in NUXT component

Upvotes: 0

Emmanuel Neni
Emmanuel Neni

Reputation: 333

The issue comes while loading your image via vue loader and webpack as the file extensions (.png, .svg, etc) are not module requests (read more about handling assets with vue loader).

You'll need to wrap it in the require to access it. the example by @Toni Michel Caubet works because he is using a link.

This Works for me.

methods: {
    setFallbackImageUrl(event) {
        console.log('Image failed to load, setting fallback.')
        event.target.src = require(`~/assets/icons/${'avatar' + '.svg'}`)
    }
}

Note: it's not needed to wrap the image in "${'avatar' + '.svg'}" i just removed my dynamic values and added "avatar".

Upvotes: 1

Related Questions