我正在使用 Vue 制作一个照片库。我创建了一个名为 Photo 的 JS 类
class Photo {
constructor(img, name) {
this.img = img;
this.name = name;
}
}
然后我将该类传递给 photoGallery 数组
data: {
photoGallery: [
new Photo(
'img/pic-1.jpg',
'Picture One'
),
new Photo(
'img/pic-2.jpg',
'Picture Two'
)
]
}
并将数组中的所有照片输出到列表中
<ul class="gallery" id="gallery">
<li v-for="photo in photoGallery" class="photo"
:style="{'backgroundImage': 'url(' + photo.img + ')'}"></li>
</ul>
我在输出的照片上方还有一个图像标签
<div class="selected-photo" id="selected-photo">
<img src="#">
</div>
我想要的是创建一个方法,该方法采用您选择的 Photo
的 img
参数,并将其推送到 img
标记中在图片列表上方。
但我不确定我将如何去做。任何帮助将不胜感激。
最佳答案
你还可以有一个数据变量:比如 selectedIdx
,它将有所选图像的索引:
data: {
photoGallery: [
new Photo(
'img/pic-1.jpg',
'Picture One'
),
new Photo(
'img/pic-2.jpg',
'Picture Two'
)
],
selectedIdx: null
}
在 v-for
中,您可以使用 v-on:click 设置此变量或 @click
如下所示:
<ul class="gallery" id="gallery">
<li v-for="(photo, idx) in photoGallery" class="photo" @click="selectedIdx = idx"
:style="{'backgroundImage': 'url(' + photo.img + ')'}"></li>
</ul>
现在有了这个,您可以在 v-bind 的帮助下在 img
标签中使用它或者用 :
简而言之:
<div class="selected-photo" id="selected-photo">
<img :src="photoGallery[selectedIdx].img" > //I am not sure which method will give you image path
</div>
关于javascript - VueJS : How can I get the parameter of the class that was clicked on?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906265/