0

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"], }, 
3
  • In <template> you're calling getImage but in controller you define getImageUrl. Commented Oct 17, 2022 at 20:58
  • I made a typo while I was typing it Commented Oct 17, 2022 at 22:03
  • Can you try with image("/" + folderName + "/" + imageName) ? Without . dot inside image() Commented Oct 18, 2022 at 17:24

1 Answer 1

1

getImage should require and return the image using the image's full relative filepath

Vue 2.x

getImage(folderName, imageName) { return require(`@/assets/${folderName}/${imageName}`) } 

Vue 3.x + Vite

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; } 
Sign up to request clarification or add additional context in comments.

5 Comments

I made it this way, it didn't work
are you using Vue 2 or Vue 3?
I’m using Vue 3
I've updated my answer with the Vue 3 solution
unfortunately, it doesn't work , bro thanks for your efforts I really got you struggling with my issues, I’m gonna drop this project out cause I’m stuck with this problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.