(Vue.js)模态关闭事件 [英] (Vue.js) modal close event
问题描述
当我单击模态的外部区域时,我想要与模态的关闭按钮相同的事件.(单击模态外部区域时关闭模态的事件)
When I click on the outer area of the modal, I want the same event as the close button of the modal. (Event that closes modal when clicking outside area of modal)
当前进度是单击关闭模态按钮时模态已关闭.
The current progress is that the modal is closed when the close modal button is clicked.
Carousel.vue
<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>
Modal.vue
<template>
<transition name="modal">
<div class="modal-mask" @click="$emit('close')">
<div class="modal-wrapper">
<div class="app__phone">
<div class="feed">
<div class="post">
<div class="header headroom">
<div class="level-left">
<img src="../assets/imgs/user.gif" class="modal-header-img"/>
<div class="user">
<span class="username">username</span>
<button class="modal-default-button" @click="$emit('close')">Close</button>
</div>
</div>
</div>
<slot name="modal-img"></slot>
<div class="content">
<div class="content-title">
<slot name="modal-tit"></slot>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</transition>
</template>
当我在底部添加click事件时,当我在模态外部单击时,它会关闭,但是当我在模态中的任何位置单击时,它会关闭.
When I add a click event to the bottom , it closes when I click outside the modal, but it closes when I click anywhere in the modal.
<div class="modal-mask" @click="$emit('close')">
并且此链接在已接受的问题答案中有一个Fiddle示例.
And this link has a Fiddle example in the accepted answer to the question.
https://stackoverflow.com/a/58023701/12066654
推荐答案
您需要像这样向外部模式div添加一个处理程序:
You need to add a handler to the outer modal div like so:
<template id="modal">
<div class="modal" @click.self="close">
<div class="close" @click="close">×</div>
<div class="body">
<slot name="body" />
</div>
</div>
</template>
这篇关于(Vue.js)模态关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!