javascript - VueJS : How can I get the parameter of the class that was clicked on?

标签 javascript jquery html css vue.js

我正在使用 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>

我想要的是创建一个方法,该方法采用您选择的 Photoimg 参数,并将其推送到 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/

相关文章:

c# - Javascript 与 C#

javascript - 为什么 toString() 和 this.toString() 在 Chrome 的控制台中产生不同的结果?

jquery - 将元素悬停后保持 div 打开

HTML- 焦点高亮边框上的选择框

CSS 按钮样式不起作用

html - 在一个div中垂直平均划分段落

javascript - Chrome 扩展;如何获取所有选项卡,将选项卡信息存储到数组?

Javascript 检查数组中的重复对象并将值合并到数组中

jquery - 每个组件完成加载后如何在 Angular 2 中运行 jquery 函数

jQuery ajax 请求使用 jsonp 错误