Reputation: 1
I'm a beginner at vue.js and I'm trying to show images dynamically but I'm having an issue with displaying them dynamically, if I change them manually it works I found many similar problems with a bit of difference none of them have helped me
this is my structure:
-src
--assets
---pizza
----pizza-1.jpg
----pizza-2.jpg
---hamburger
----hamburger-1.jpg
----hamburger-2.jpg
---french-fries
----french-fries-1.jpg
----french-fries-2.jpg
--components
--DBjson
---main.json
I'm trying to make this loop
`<div class="holder" v-for="restaurant in restaurants">
<img :src="getImage(restaurant.name, restaurant.mainImage)"/>
</div>
export default {
name: "restaurant",
data() {
return {
restInfo: this.$attrs.restData,
};
},
methods: {
getImage(folderName, imageName) {
let image = require.context("@/assets/");
return image("./" + folderName + "/" + imageName);
},
},
};`
my JSON file
{
"id": 1,
"name": "pizza",
"price": "$10",
"mainImage": "pizza-1.jpg",
"images": ["pizza-2.jpg", "pizza-1.jpg"],
},
Upvotes: 0
Views: 73
Reputation: 14639
getImage should require and return the image using the image's full relative filepath
getImage(folderName, imageName) {
return require(`@/assets/${folderName}/${imageName}`)
}
Vite as far as I know can't handle '@' alias for this particular task so be sure to set your path accordingly
getImage(folderName, imageName) {
return new URL(`../assets/${folderName}/${imageName}`, import.meta.url).href;
}
Upvotes: 1