Skip to content
Advertisement

How to use source images dynamically in :src in Vuejs

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement