vuejs data binding on img src attribute give 404 error

Issue

I tried to bind the img src attribute to a variable for the path of the image, and it didn’t work. But if I copied and pasted the the same path in, then it works. Where did I get things wrong?

The error message: http://localhost:8080/@/assets/result-images/Soya-bean.jpg 404 (Not Found)

<template>
  <img :src= "imgSrc" alt="No image available"/>      //This doesn't work
  <img src= "@/assets/result-images/Soya-bean.jpg" alt="No image available"/>  //This works
</template>

<script>
import {ref} from 'vue'
export default {
  setup(){
    const imgSrc = ref()
    imgSrc.value = "@/assets/result-images/Soya-bean.jpg"
    return{imgSrc}
  }
}
</script>

What it looks like on the browser

Solution

imgSrc.value = require("@/assets/result-images/Soya-bean.jpg");

should do it.

Documentation here.

Answered By – tao

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.