there is a vue.js component which is taking an object as a prop from the main App.
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 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.
Solution :
You need to use require to make Webpack resolved the path correctly
<img :src=”getImage(object.image)” :alt=’object.name’>
methods: {
getImage(path) {
return require(path)
}
}
Solution 2:
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>