VUE realizes that the pop-up box disappears when you click on a blank page
You can implement a pop-up box in Vue and then hide the pop-up window by clicking on a blank page. The specific implementation is as follows:
- Create popup box component
Create a pop-up box component in Vue to present the content and style of the pop-up box. This component should accept two props, one is show, which indicates whether the pop-up box is displayed, and the other is onClose, which indicates the closing function of the pop-up box.
<template>
<div v-if="show" class="modal">
<div class="modal-body">
<slot></slot>
<button @click="onClose">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: ['show', 'onClose']
}
</script>
- Create parent component
Use the above pop-up box component in the parent component, bind a click event to the document in the blank area, and close the pop-up box when the non-pop-up box area is clicked.
<template>
<div class="page">
<button @click="showModal = true">弹出框</button>
<modal :show="showModal" :onClose="closeModal">
<p>这是弹出框的内容</p>
</modal>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: {
Modal
},
data() {
return {
showModal: false
}
},
created() {
document.addEventListener('click', this.onClickOutside);
},
beforeDestroy() {
document.removeEventListener('click', this.onClickOutside);
},
methods: {
onClickOutside(event) {
if (this.showModal && !this.$el.contains(event.target)) {
this.closeModal();
}
},
closeModal() {
this.showModal = false
}
}
}
</script>
In the parent component, we use the v-if directive to determine whether the pop-up box is displayed. At the same time, we bound a click event to the document in the created hook function to listen for click events on the page. In the onClickOutside method, if the current pop-up box is displayed and the clicked element is not an element within the pop-up box, close the pop-up box. In the closeModal method, we set showModal to false to hide the popup box component.
- Add style
Finally, we add some simple styles to the popup and parent components.
<style>
.page {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.modal {
position: absolute;
top: 0;
left: 0;
z-index: 1000;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-body {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
}
</style>
The above is the entire code implementation of Vue to realize that the pop-up box disappears when you click on a blank page.