Vue.js dynamic picture display function fails
P粉216807924
2023-08-20 11:03:39
<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>
getImage should ask for and return an image using its full relative file path
Vue 2.x
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