Search code examples
vue.jsmodal-dialogpopupv-for

(vue.js) When clicking on an image, I want to call a modal for each image


When clicking on an image, I want to call a modal for each image.

There are currently 3 images and clicking on the image brings up a modal without content.

Here is what my directory looks like:

components

ㅡcommon

ㅡㅡModal.vue

ㅡContent.vue

ㅡDetail.vue

App.vue

data () {
    return {
      imgItems: [
        {
          thumbnail: require('./assets/imgs/aa.jpg'),
          description: 'aa'
        },
        {
          thumbnail: require('./assets/imgs/bb.jpg'),
          description: 'bb'
        },
        {
          thumbnail: require('./assets/imgs/cc.jpg'),
          description: 'cc'
        }
      ]
    }
  }

Content.vue

<template>
  <div class="container">
    <div class="gallery">
      <ul>
        <li v-for="(item, index) in items" :key="index">
          <img :src="item.thumbnail" class="gallery-image">
          {{ item.thumbnail }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    items: { type: Array, default: () => [] }
  }
}
</script>

I hope you can help me. thanks!XD


Solution

  • In the image, add an v-on click event at the tags, linking it to a method:

     <img :src="item.thumbnail" class="gallery-image" @click="modalHandler">
    

    you can also do this:

    <img :src="item.thumbnail" class="gallery-image" @click="showModal = !showModal">
    

    Then, you must add some new data to your data classes, to toggle the modal:

    data () {
    return {
      imgItems: [
        {
          thumbnail: require('./assets/imgs/aa.jpg'),
          description: 'aa'
        },
        {
          thumbnail: require('./assets/imgs/bb.jpg'),
          description: 'bb'
        },
        {
          thumbnail: require('./assets/imgs/cc.jpg'),
          description: 'cc'
        }
      ],
      showModal: false
    }
    

    }

    Then, at your HTML page, go to the MODAL and use a v-if to only render it when showModal = true

    <modal v-if="showModal">