Vue.js dynamic picture display function fails
P粉216807924
P粉216807924 2023-08-20 11:03:39
0
1
577
<p>I'm a beginner with vue.js and I'm trying to dynamically display images but I'm having trouble with the dynamic display, if I change them manually they work fine. I found many similar questions with some differences and none of them helped me. </p> <p>This is my structure: </p> <pre class="brush:php;toolbar:false;">-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</pre> <p>I'm trying to create this loop: </p> <pre class="brush:php;toolbar:false;">`<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); }, }, };`</pre> <p>My JSON file: </p> <pre class="brush:php;toolbar:false;">{ "id": 1, "name": "pizza", "price": "$10", "mainImage": "pizza-1.jpg", "images": ["pizza-2.jpg", "pizza-1.jpg"], },</pre>
P粉216807924
P粉216807924

reply all(1)
P粉798343415

getImage should ask for and return an image using its full relative file path

Vue 2.x

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

Vue 3.x Vite

As far as I know, Vite cannot handle the '@' alias for this specific task, so make sure to set your paths accordingly

getImage(folderName, imageName) {
  return new URL(`../assets/${folderName}/${imageName}`, import.meta.url).href;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template