Vue實現(xiàn)彈出框點擊空白頁彈框消失效果
VUE實現(xiàn)彈出框 點擊空白頁彈框消失
可以在Vue中實現(xiàn)彈出框然后通過點擊空白頁面來讓彈窗隱藏。具體實現(xiàn)如下:
創(chuàng)建彈出框組件
在Vue中創(chuàng)建一個彈出框組件,用來呈現(xiàn)彈出框的內容和樣式。該組件應該接受兩個 props,一個是 show,表示彈出框是否顯示,另一個是 onClose,表示彈出框的關閉函數(shù)。
<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>創(chuàng)建父組件
在父組件中使用上述彈出框組件,同時在空白區(qū)域給document綁定點擊事件,在點擊非彈出框區(qū)域時關閉彈出框。
<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>在父組件中,我們使用 v-if 指令來判斷彈出框是否顯示。同時,我們在 created 鉤子函數(shù)中給 document 綁定了一個點擊事件,用來監(jiān)聽頁面的點擊事件。在 onClickOutside 方法中,如果當前彈出框顯示,并且點擊的元素不是彈出框內的元素,則關閉彈出框。在 closeModal 方法中,我們將 showModal 設置為 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)。
到此這篇關于VUE實現(xiàn)彈出框 點擊空白頁彈框消失的文章就介紹到這了,更多相關vue彈出框內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue前端測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化
這篇文章主要為大家介紹了vue測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
在vue中路由使用this.$router.go(-1)返回兩次問題
這篇文章主要介紹了在vue中路由使用this.$router.go(-1)返回兩次問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
在vue項目中promise解決回調地獄和并發(fā)請求的問題
這篇文章主要介紹了在vue項目中promise解決回調地獄和并發(fā)請求的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

