Home > Mobile >  How to use source images dynamically in :src in Vuejs
How to use source images dynamically in :src in Vuejs

Time:07-26

I've tried everything I found on Google, none of they worked for me.

Basically, what I'm trying to do is passing an object through a v-for to another component like that:

<Representante
    v-for="(representante, i) in representantes"
    :key="i"
    :rep="representante"
/>

This representante variable is the object i'm passing. It has a imagem property that contains the name of the image I need.

IMPORTANT: the images are in the public folder because I thought it would work, but it hasn't.

Inside the component script, here's what I have:

<script>

    export default {
        props: ['rep'],
        data() {
            return {
                foto: null
            }
        },
        mounted() {
            this.foto = '/'   this.rep.imagem;
        }
    }

</script>

That basically initializes the foto property in data(), so I can use in the <img> tag.

<img :src="foto" :alt="rep.altImagem">

But it simply doesn't work, neither with the image on the public folder nor the src/assets/ folder. Only the alt is displayed. I've tried using require() too, but it doesn't work like that, or I didn't know how to use.

I can't find any information on the internet of why Vue isn't able to find my images.

By the way, thats the error I get:

GET http://localhost:8080/nameOfImage.jpeg [HTTP/1.1 404 Not Found 3ms]

Thanks any help.

CodePudding user response:

If you have the images in the public folder (and not a subfolder like public/assets or public/images) then this would work.

couple things worth checking:

  • the filename matches. extension jpeg vs jpg or case
  • that you do not have them in a subdirectory within public (or include it in your variable ie: this.foto = '/images/' this.rep.imagem;

CodePudding user response:

My solution was to add the images on a remote repository so I could get the URLs and use them, that worked. But I still think my problem is very weird behavior of Vue.

  • Related