Vue.js 在Vue中尝试将v-for与v-if一起使用
我有一个数组的照片,我需要,在加载页面之前,改变图像的SRC 例如:Vue.js 在Vue中尝试将v-for与v-if一起使用,vue.js,vue-component,Vue.js,Vue Component,我有一个数组的照片,我需要,在加载页面之前,改变图像的SRC 例如: images: [ { name: 'Car', image: require('../assets/car.png') }, { name: 'Book', image: require('../assets/book.png') }, ] 和我的模板代码: <div v-for="(item, index) in images" :key=index> <div v-if="item.
images: [
{ name: 'Car', image: require('../assets/car.png') },
{ name: 'Book', image: require('../assets/book.png') },
]
和我的模板代码:
<div v-for="(item, index) in images" :key=index>
<div v-if="item.name=="selectedItem"
<img :src="item.image" width="100px" height="auto">
</div>
</div>
我怎么能做到
当我尝试此操作时,我得到selectedItem在渲染时未定义您应该使用函数返回所需的内容。比如:
<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>
如果筛选后的selectedSrc数组中有多个结果,则只会得到第一个结果。考虑到您的图像数组不是动态数组,它应该可以正常工作。在中,避免将v-if
与v-for
一起使用
通过使用computed
属性对数据进行预过滤,使模板
纯粹用于显示数据,可以重构上述代码。我猜selectedItem
是作为props
传递的吧?下面是代码:
<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);
}
}
道具:{selectedItem},
数据(){
返回{
图像:[
{名称:'Car',图像:'../assets/Car.png'},
{名称:'Book',图像:'../assets/Book.png'},
]
};
},
计算:{
选定的(){
返回this.images.find(img=>img.name==selectedItem);
}
}
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;
},
}
<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);
}
}