I am trying to create a page where I show Pizza items with their images. The Pizza object is saved in the DB with a field imgUrl
. The image is not getting displayed but I see the alt
text that I provided but I can see in the console that the image link is correct.
Right now, the imgUrl field in the database has data like ../assets/images/pizza.jpg
. Should I instead save require(../assets/images/pizza.jpg)
in the db. That looks weird. Here is the code, please look at the mounted method.
<template>
<div>
<div class="class">
<span><h1>All you can eat Menu.</h1></span>
<div class="container">
<div class="box" v-for="item in pizzaList" :key="item.id">
<div>
<img :src="item.imgUrl" alt="Image"/>
<div>
<a class="btn" @mouseenter="$event.currentTarget.style.background = '#EF6B7F'"
@mouseleave="$event.currentTarget.style.background = '#e31837' ">Buy Now</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data () {
return {
pizzaList: []
}
},
mounted: function () {
axios.get('http://localhost:8081/api/pizza/all')
.then(response => {
this.pizzaList = response.data;
})
.catch(e => {
console.log(e);
})
}
}
</script>
I have already read Vue and API: Displaying Image Image path in Vue JS How to reference static assets within vue javascript
but what these answers are telling is how to do when we have hardcoded the url, we should encapsulate it with require
but they do not tell when we are getting the link from the DB, how do we put require
in the html tag. I hope my question was clear. Please ask for details if you need. thanks
The reason it was not working was because
Webpack's require() needs at least some part of the file path to be completely static and we should "make only part of the path dynamic"
that means you cannot put the entire image path in the DB and in the UI pass it to require
and expect it to work
I replaced
<img :src="require(`${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '../assets/entities/pizza/pizza_1.jpg
' (which is the entire image path relative to the component)
by
<img :src="require(`../assets${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '/entities/pizza/pizza_1.jpg
'
This answer mentioned by Michal Levy
up in the comments explains all this https://stackoverflow.com/a/64208406/8147680
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments