2

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?

Dominik
  • 4,718
  • 13
  • 44
  • 58
  • That's strange: [it work's in an example that I've set up](https://jsfiddle.net/teddyrised/uh2qes45/). Can you check from your browser's network tab if the image is being loaded correctly? Is there, by any chance, that the `article.author_image` changes after the `setFallbackImageUrl(()` is invoked? – Terry Feb 08 '19 at 17:08
  • what does `console.log(event.target)` look like? – Toni Michel Caubet Feb 08 '19 at 17:35
  • @Terry the image doesn't load if you open it in a tab, it is an incorrect URL path that points to my endpoints image without having the full url Author Image. – Dominik Feb 08 '19 at 21:34
  • This only works for images with a url, not for missing images in assets or static folder. – mahatmanich Mar 24 '22 at 14:24

2 Answers2

1

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".

Emmanuel Neni
  • 325
  • 4
  • 11
  • This only works for images that are not handled via webpack or static folder. The original src needs to be a url and not called via require or ~/assets or ~/static. – mahatmanich Mar 24 '22 at 14:53
0

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

mahatmanich
  • 10,791
  • 5
  • 63
  • 82