Search code examples
vue.jsindexingpopupgallery

Use popup gallery with index


Hi I am a beginner on learning Vue. I want to shorten my popup code with index. But I don't know how to make it clearly.
Can you tell me how to give my images some attributes to control the popup if it shows or not. Or Other methods to solve it.
Here is my code. Thank you.

<div class="image" v-for="(img, index) in images" :key="index">
  <span @click="imgClick(index)">
    <img class="initial_img" :src="require(`@/assets/picture/${img}.jpg`)" alt="">
  </span>
</div>
  <Popup :open="isOpen_1" @close="isOpen_1 = !isOpen_1">
     <img :src="require('@/assets/picture/001.jpg')"/>
  </Popup>
  <Popup :open="isOpen_2" @close="isOpen_2 = !isOpen_2">
     <img :src="require('@/assets/picture/002.jpg')"/>
  </Popup>
</div>
</script>
import Popup from "../components/Popup.vue"
import {ref} from "vue"

export default {
    components: {
        Popup,
    },
    setup(){
        const isOpen_1 = ref(false);
        const isOpen_2 = ref(false);
        return {isOpen_1, isOpen_2}
    },

    data() {
        return{
            images:['001','002'],
        }
    },
methods:{
        closeAllisOpen(){
            this.isOpen_1 = false;
            this.isOpen_2 = false;
        },
        imgClick(index){
            this.closeAllisOpen();
            switch(index){
                case 0: this.isOpen_1 = true; break
                case 1: this.isOpen_2 = true; break
            }
        },
    }
}
</script>

Solution

  • Maybe you can make your photos to object in script. Like the blow.

    images:[{src:require("your path"),}]
    
    

    Then control isOpen with methods to choose which one should be popup now.

    <Popup :open="isOpen" @close="isOpen = !isOpen">
          <template #img><img :src="images[imgIndex].src"/></template>
    </Popup>
    
    imgClick(index){
                this.isOpen = true;
                switch(index){
                    case 0: this.imgIndex = 0; break...
                }
            },