(Vue.js)我想使图像1在单击图像1时弹出,而我想使图像2在单击图像2时弹出. [英] (Vue.js) I want to make image 1 pop up when I click on image 1, and I want image 2 to pop up when I click on image 2

查看:552
本文介绍了(Vue.js)我想使图像1在单击图像1时弹出,而我想使图像2在单击图像2时弹出.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几张图像.我想使图像1在单击图像1时弹出,而我想使图像2在单击图像2时弹出.我可以使用类中的索引来解决它吗?

There are several images. I want to make image 1 pop up when I click on image 1, and I want image 2 to pop up when I click on image 2. Can I solve it using the index in class?

Carousel.vue

<template>
  <div v-for="(item, index) in items" :key="index">
    <img :src="item.thumbnail" />
    <button type="button" @click="imgClick()" :class="`img-index--${index}`">button-{{ index }}</button>
  </div>
  <Modal v-if="showModal" @close="showModal = false">
    <div slot="body" v-for="(item, index) in items" :key="index">
      <img :src="item.thumbnail" :class="`img-index--${index}`"/>
    </div>
  </Modal>
</template>

<script>
import Modal from './Modal.vue'
export default {
  props: {
    items: { type: Array, default: () => [] }
  },
  data() {
    return {
      showModal: false
    }
  },
  methods: {
    imgClick() {
      this.showModal = !this.showModal;
    }
  },
  components: {
    Modal: Modal
  }
}
</script>

推荐答案

您可以从items道具构建新数据,并为每个图像注入新属性show: false.

You can build a new data from your items prop and inject a new property show: false for each image.

您不需要2个v-for这样的循环.您可以将Modal组件放入第一个循环中,而只需使用item.show来显示或不显示模态.

You don't need 2 v-for loops this way. You can put the Modal component inside the first loop and just use the item.show to display or not the modal.

<template>
  <div>
    <div v-for="(item, index) in photos" :key="index">
      <div @click="imgClick(item)" style="cursor:pointer;>
        <img :src="item.thumbnail" />
      </div>
      <Modal v-if='item.show' @close="item.show = false">
        <div slot='body'>
          <img :src="item.thumbnail" :class="`img-index--${index}`"/>
        </div>        
      </Modal>
    </div>
  </div>
</template>

<script>
import Modal from './Modal.vue'
export default {
  props: {
    items: { type: Array, default: () => [] }
  },
  data() {
    return {
      photos: {}
    }
  },
  created() {
    this.photos = this.items.map(item => {
      return { ...item, show: false }
    })
  },
  methods: {
    imgClick(item) {
      item.show = true
    }
  },
  components: {
    Modal: Modal
  }
}
</script>

小提琴示例此处

注意:您可以将缩略图包裹在div中以管理点击图像.

Note: you can wrap the thumbnail inside a div to manage the click image.

这篇关于(Vue.js)我想使图像1在单击图像1时弹出,而我想使图像2在单击图像2时弹出.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆