Home > front end >  Why does binding a variable to the src parameter in the img tag not work in vuejs?
Why does binding a variable to the src parameter in the img tag not work in vuejs?

Time:11-28

I have a Vuejs component containing an img tag. I can render the image with no problem if I hardcode the src like this.

<template>
    <div>
        <!-- <img  alt="Vue logo" src="@/assets/abstractwave.png"/> -->
    </div>
</template>

<script>
export default {
    name: "RotatingImage",
    props: {
        filename: String
    },

}
</script>

I cannot render the image if I insert bind the src as a prop. As follows... Why is this? What must I change in order to render the image using a prop?

<template>
    <div>
        <img class = "rotate" alt="Vue logo" :src="`@/assets/${filename}`" />
    </div>
</template>

<script>
export default {
    name: "RotatingImage",
    props: {
        filename: String
    },

}
</script>

Upon inspection in the browser, I see that the src path is correct, yet the image does not show.

CodePudding user response:

You can make computed property:

computed: {
  getImgUrl() { 
     return require(`@/assets/${this.filename}`);
  }
}

Then in template bind it:

<img class = "rotate" alt="Vue logo" :src="getImgUrl" />
  • Related