1

I have a Vue component which is taking an object as a prop from the main App.

I want to access a property in that object which contains the url to the image source.

The url changes correctly. If, for example, the object's 'image' property is '../assets/image.png' then the src="" will point to the correct path but nothing will show.

If I put the url in the image src manually '../assets/image.png', the image displays no problem. But I want it to be dynamic.

<img :src="object.image" :alt='object.name'>

.name displays fine, but .image comes up with no image, even if the path is correct.

2 Answers 2

0

It is a common issue that people use Vue. The problem is that webpack does not correctly format the binded object because expression in v-bind is executed at runtime, webpack aliases at compile time, to do that you can use webpacks require() function

methods: {
   getImgUrl(imgName) {
    return require('../assets/'+imgName)
   }
},
data () {
    return {
       object: {
          image: 'image.png'
       }
    }
}

In the template, you can get the image src as

<div>
    <img :src="getImgUrl(object.image)" :alt="object.image">
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use require to make Webpack resolved your path correctly

<img :src="getImage(object.image)" :alt='object.name'>

methods: {
  getImage(path) {
    return require(path)
  }
}

Comments

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.