Vue實現(xiàn)彈出框點擊空白頁彈框消失效果
VUE實現(xiàn)彈出框 點擊空白頁彈框消失
可以在Vue中實現(xiàn)彈出框然后通過點擊空白頁面來讓彈窗隱藏。具體實現(xiàn)如下:
創(chuàng)建彈出框組件
在Vue中創(chuàng)建一個彈出框組件,用來呈現(xiàn)彈出框的內(nèi)容和樣式。該組件應(yīng)該接受兩個 props,一個是 show,表示彈出框是否顯示,另一個是 onClose,表示彈出框的關(guān)閉函數(shù)。
<template>
<div v-if="show" class="modal">
<div class="modal-body">
<slot></slot>
<button @click="onClose">關(guān)閉</button>
</div>
</div>
</template>
<script>
export default {
props: ['show', 'onClose']
}
</script>創(chuàng)建父組件
在父組件中使用上述彈出框組件,同時在空白區(qū)域給document綁定點擊事件,在點擊非彈出框區(qū)域時關(guān)閉彈出框。
<template>
<div class="page">
<button @click="showModal = true">彈出框</button>
<modal :show="showModal" :onClose="closeModal">
<p>這是彈出框的內(nèi)容</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>在父組件中,我們使用 v-if 指令來判斷彈出框是否顯示。同時,我們在 created 鉤子函數(shù)中給 document 綁定了一個點擊事件,用來監(jiān)聽頁面的點擊事件。在 onClickOutside 方法中,如果當前彈出框顯示,并且點擊的元素不是彈出框內(nèi)的元素,則關(guān)閉彈出框。在 closeModal 方法中,我們將 showModal 設(shè)置為 false,用來隱藏彈出框組件。
添加樣式
最后,我們?yōu)閺棾隹蚝透附M件添加一些簡單的樣式。
<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>以上是Vue實現(xiàn)彈出框點擊空白頁彈框消失的全部代碼實現(xiàn)。
到此這篇關(guān)于VUE實現(xiàn)彈出框 點擊空白頁彈框消失的文章就介紹到這了,更多相關(guān)vue彈出框內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue項目之ES6裝飾器在項目實戰(zhàn)中的應(yīng)用
作為一個曾經(jīng)的Java?coder,當?shù)谝淮慰吹絡(luò)s里面的裝飾器Decorator,就馬上想到了Java中的注解,當然在實際原理和功能上面,Java的注解和js的裝飾器還是有很大差別的,這篇文章主要給大家介紹了關(guān)于Vue項目之ES6裝飾器在項目實戰(zhàn)中應(yīng)用的相關(guān)資料,需要的朋友可以參考下2022-06-06
Vue通過字符串關(guān)鍵字符實現(xiàn)動態(tài)渲染input輸入框

