我有一系列来自道具的物体。每个对象都有一个标题和img键值。我正在使用v-for显示标题以及img值中的图像。
<div v-for="item in products" :key="item.id">
<h1>{{item title}}</h1>
<img :src="item.img">
</div>
export default {
name: "home",
props: ["products"]
/*
here is the products
[{id: 1, title: "Moe", img: "../assets/images/stooges/moe.jpg"},
{id: 2, title: "Larry", img: "../assets/images/stooges/larry.jpg"},
{id: 3, title: "Curly", img: "@/assets/images/stooges/curly.jpg"}]
*/
};
在最后一个元素上,我正在尝试相对引用。我也尝试过这样的事情
<img :src="require(item.img)">
至少对于最后一个元素,我希望看到图像。
答案 0 :(得分:2)
<div v-for="item in products" :key="item.id">
<h1>{{ item.title }}</h1>
<img :src="require(`@/assets/images/stooges/${item.img}.jpg`)" />
</div>
export default {
name: "home",
props: ["products"]
data() {
return {
products: [
[{id: 1, title: "Moe", img: "moe"},
{id: 2, title: "Larry", img: "larry"},
{id: 3, title: "Curly", img: "curly"}]
]
};
},
};