1

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

1 Answer 1

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

should do it.

Documentation here.

Sign up to request clarification or add additional context in comments.

2 Comments

So, i should use require() everytime when i want to bind the src html attribute?
@minas, yes, that's correct. This is because the files are provided from different places while serving versus the deployed build. vue-loader does a lot of work behind the scenes, but you need to use require().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.