2

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 ?

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

2 Answers 2

3

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'"
Sign up to request clarification or add additional context in comments.

1 Comment

Does not work on Nuxt3 anymore.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.