0👍
You should use a function to return what you want. Something like:
<div v-for="(image, index) in images" :key=index>
<div v-if="selectedSrc.length"
<img :src="getSelectedSrc(image.name)" width="100px" height="auto">
</div>
</div>
Note that, to check selectedSrc length in this case, is irrelevant, since you are running a loop inside an array that will always have a filtered result.
Inside your Vue declarations:
data() {
return {
images: [
{ name: 'Car', image: '../assets/car.png' },
{ name: 'Book', image: '../assets/book.png' },
],
selectedSrc: [],
};
},
methods: {
getSelectedSrc(name) {
this.selectedSrc = this.images.filter(item => item.name === name);
return this.selectedSrc[0].image;
},
}
If you have more than one result inside the filtered selectedSrc array, you will get just the first result. Considering your images array being not a dynamic array, it should work fine.
- [Vuejs]-Html file src path errror and 404 not found
- [Vuejs]-How can I publish my vue project on github pages?
0👍
In the Vue style guide, avoid using v-if
with v-for
is essential.
Your code above can be refactored by prefilter the data with computed
property, make the template
for purely displaying data. I guess selectedItem
is passed as props
? then here is the code:
<div v-if="selected">
<img :src="selected.image" width="100px" height="auto">
</div>
props: { selectedItem },
data() {
return {
images: [
{ name: 'Car', image: '../assets/car.png' },
{ name: 'Book', image: '../assets/book.png' },
]
};
},
computed: {
selected() {
return this.images.find(img => img.name == selectedItem);
}
}
Source:stackexchange.com