1

I have a card component which has a structure for an image like this. One image can't be loaded because of (HTTP Status: 403). So I want to replace it with a default one. So I looked it up and learn that I can use @error.


<div class="card-thumbnail">
    <img
       :src="cardImage"
        alt=""
        @error="$event.target.src = '~/assets/images/error.jpeg'"
     />
</div>

However this code gives me error that "error.jpeg" can not be found. My folder structure is correct because without @error and a src like this:

src="~/assets/images/error.jpeg"

I can actually see my error.jpeg. So what I am doing wrong here ?

omerS
  • 817
  • 2
  • 9
  • 21
  • Try out `@error="$event.target.src = require('~/assets/images/error.jpeg')"` – Boussadjra Brahim Jul 14 '21 at 11:37
  • You need to use the require syntax like here https://stackoverflow.com/a/66365980/8816585 also, why do you do an affectation. Wanted to write $emit("something", "error.jpg")`? – kissu Jul 14 '21 at 11:38
  • @BoussadjraBrahim yep that works. But why ? I mean it is not dynamic tho. It is a static file in my folder – omerS Jul 14 '21 at 11:40
  • @kissu I am not sure I understood the affectation thing – omerS Jul 14 '21 at 11:40

2 Answers2

2

Nuxt 2

Based on this you need to use require because images inside assets directory are considered as modules :

@error="$event.target.src = require('~/assets/images/error.jpeg')" 

Nuxt 3

if the image is in public folder :

   @error="$event.target.src = '/images/error.jpeg'"

if it's in assets folder :

  @error="$event.target.src = '~/assets/images/error.jpeg'"
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
0

Nuxt3 Solution:

<template>
<div class="card-thumbnail">
    <img
       :src="cardImage"
        alt=""
        @error="$event.target.src = image"
     />
</div>
</template>

<script setup>
import image from '~/assets/images/error.jpeg'
</script>

Reference: Why loading dynamically assets fails on Nuxt v3

Stefan
  • 123
  • 1
  • 10